Filter all days between time range in R

I have a data frame as shown below:

entry_no      id            time
_________     ___           _____
1              1        2016-09-01 09:30:09
2              2        2016-09-02 10:36:18
3              1        2016-09-01 12:27:27
4              3        2016-09-03 10:24:30
5              1        2016-09-01 12:35:39
6              3        2016-09-06 10:19:45

From this, I want to filter out entries that occur between 9:00 and 10:00 every day. I know that in one day I can use something like:

results=filter(df,time>='2016-09-01 09:00:00' && time<='2016-09-01 10:00:00') 

but filter the results for each day of the month. Any help is appreciated.

+3
source share
2 answers

You can achieve this with simple formatting:

dat$hms <- format(as.POSIXct(dat$time), "%H:%M:%S")
dat[dat$hms >= "09:00:00" & dat$hms <= "10:00:00",]

#  entry_no id                time      hms
#1        1  1 2016-09-01 09:30:09 09:30:09
+4
source

I would suggest using a package lubridate.

library(lubridate)

date1 <- as.POSIXct("2016-09-01 09:00:00") #lower bound
date2 <- as.POSIXct("2016-09-01 10:00:00") #upper bound
rng <- new_interval(date1, date2)          #desired range

result <- df[df$time %within% rng,]

You may need to check the class of the variable timeand apply some changes before using the above:

df$time <- as.POSIXct(df$time)
+1
source

Source: https://habr.com/ru/post/1684168/


All Articles