6

I have a data frame like 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 the entries which occurs between the time 9 am to 10 am for every day.I know for 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 to filter out the results for every day of the month.Any help is appreciated.

M--
  • 25,431
  • 8
  • 61
  • 93
Ricky
  • 2,662
  • 5
  • 25
  • 57
  • 1
    Also don't use `&&` unless you really want to do comparison with only the first element of `df$time`. `&` is the full vectorised `AND`. – thelatemail May 30 '17 at 01:10

2 Answers2

9

You could achieve it with a bit of 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
thelatemail
  • 91,185
  • 12
  • 128
  • 188
6

I would suggest using lubridate package.

library(lubridate)

date.range <- interval(as.POSIXct("2016-09-01 09:00:00"), #lower bound
                       as.POSIXct("2016-09-01 10:00:00")  #upper bound
                       ) 

filtered.results <- df[df$time %within% date.range,]

You may need to check the class of time variable and apply some changes before getting the results:

df$time <- as.POSIXct(df$time)
M--
  • 25,431
  • 8
  • 61
  • 93