I have a data.frame
that contains a bunch of POSIXct
dates:
df <- data.frame(dte=as.POSIXct(c("2001-02-03 14:30:00",
"2001-02-04 9:30:00", "2001-02-05 10:30:00")), a=1:3)
I would like to extract the part of the df
that has the time portion greater than 9:15 AM and less than 5:25 PM. I could extract the components of hour and minute separately and write a comparison but i thought there might be a more elegant way of doing it. Can anyone make a suggestion?
My current method would be:
df <- subset(df,
(as.numeric(format(dte, "%H")) > 9 & as.numeric(format(dte, "%M")) > 15) |
(as.numeric(format(dte, "%H")) < 17 & as.numeric(format(dte, "%M")) < 25))
My suggestion would be to use xts instead of a data.frame.
df <- data.frame(dte=as.POSIXct(c("2001-02-03 14:30:00",
"2001-02-04 9:30:00", "2001-02-05 10:30:00")), a=1:3)
library(xts)
x <- xts(df$a, df$dte)
x["T09:15/T17:25"] # returns everything (in your example)
x["T10:15/T14:25"] # returns the correct subset
来源:https://stackoverflow.com/questions/11853524/comparing-time-portion-of-posixct-in-r