简体   繁体   中英

R: How do I subset based on conditional DateTime data

Here's a sample of my data:

# A tibble: 4 x 3
  Squirrel.ID  Release.time  DetectTime
        <int>  <S4: Period>  <dttm>
1       13097   13H 13M 18S 2017-05-29 18:50:43
2       20948   10H 15M 8S  2017-06-05 08:09:48
3       21853   11H 20M 33S 2017-05-24 21:57:32
4       13088   12H 13M 45S 2017-05-30 08:44:03

I'm looking to subset it for rows where hte DetectTime values occurred at least 1.5 hours before the Release.time values. For example, if I had a DetectTime value of "2017-05-30 06:00:00" and a Release.time value of "10:00:00" , then I would want to retain that row. If I had a DetectTime value of "2017-05-30 10:15:00" and a Release.time value of "10:00:00" , then I would want to exclude that row.

I'm working with dplyr and lubridate if that helps. Thank you.

Replicating your data:

library(lubridate)

df <- data.frame(Squirrel.ID = c(13097, 20948, 21853, 13088),
      Release.time = c("13H 13M 18S", "10H 15M 8S", "11H 20M 33S", "12H 13M 45S"), 
      DetectTime = c("2017-05-29 18:50:43", "2017-06-05 08:09:48", "2017-05-24 21:57:32", "2017-05-30 08:44:03"))
df$Release.time <- hms(df$Release.time)


#   Squirrel.ID Release.time          DetectTime
#1       13097  13H 13M 18S 2017-05-29 18:50:43
#2       20948   10H 15M 8S 2017-06-05 08:09:48
#3       21853  11H 20M 33S 2017-05-24 21:57:32
#4       13088  12H 13M 45S 2017-05-30 08:44:03

Solution:

library(lubridate)
df[df$Release.time - hms(strftime(df$DetectTime, format="%H:%M:%S")) >= "1H 30M",]

Output:

#  Squirrel.ID Release.time             DetectTime
#2       20948   10H 15M 8S    2017-06-05 08:09:48
#4       13088   12H 13M 45S   2017-05-30 08:44:03

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM