比较R中POSIXct的时间部分 [英] comparing time portion of POSIXct in R

查看:768
本文介绍了比较R中POSIXct的时间部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data.frame ,其中包含一堆 POSIXct 日期:

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)

我想提取时间部分大于9:15 AM而小于等于的$ df 的部分下午5:25我可以单独提取小时和分钟的组件,并写一个比较,但我认为可能会有一个更优雅的方式来做。任何人都可以提出建议?

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?

我目前的方法是:

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


推荐答案

我的建议是使用xts而不是data.frame。 p>

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

这篇关于比较R中POSIXct的时间部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆