comparing time portion of POSIXct in R

╄→гoц情女王★ 提交于 2019-12-08 10:00:50

问题


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))

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!