早高峰时间的 R 检验 - 区间内的时间向量

标签 r time lubridate

我正在尝试在 R 中创建一个干净的函数,如果 POSIXlt 时间向量处于早高峰时段(即周一至周五上午 7.30 至 9.30),则返回 TRUE/FALSE。这就是我到目前为止所做的,但看起来有点长而且令人费解。是否可以在保持代码本身可读性的同时对此进行改进?

library(lubridate)

morning.rush.hour <- function(tm) {
  # between 7.30am and 9.30am Monday to Friday
  # vectorised...
  # HARDCODED times here!
  tm.mrh.start <- update(tm, hour=7, minute=30, second=0)
  tm.mrh.end <- update(tm, hour=9, minute=30, second=0)
  mrh <- new_interval(tm.mrh.start, tm.mrh.end)
  # HARDCODED weekdays here!
  ((tm$wday %in% 1:5) & # a weekday?
         (tm %within% mrh))
}
# for test purposes...
# nb I'm forcing UTC to avoid the error message "Error in as.POSIXlt.POSIXct(x, tz) : invalid 'tz' value"
#   - bonus points for solving this too :-)
tm <- with_tz(as.POSIXlt(as.POSIXlt('2012-07-15 00:00:01', tz='UTC') + (0:135)*3000), 'UTC')
data.frame(tm, day=wday(tm, label=TRUE, abbr=FALSE), morning.rush.hour(tm))

如果像这样的工作日时间范围有一个干净的函数定义就更好了,因为我也有晚上高峰时间,以及非高峰时间的白天,最后没有这些!

最佳答案

我会做一些比使用 difftimecut 更简单的事情。您可以执行以下操作(使用 base 函数):

morning.rush.hour<-function(tm){
    difftime(tm, cut(tm, breaks="days"), units="hours") -> dt  #This is to transform the time of day into a numeric (7:30 and 9:30 being respectively 7.5 and 9.5)
    (tm$wday %in% 1:5) & (dt <= 9.5) & (dt >= 7.5)  #So: Is it a weekday, it is before 9:30 and is it after 7:30?
    }

编辑:如果需要,您还可以向 difftime 添加时区参数:

difftime(tm, cut(tm, breaks="days"), units="hours", tz="UTC")

关于早高峰时间的 R 检验 - 区间内的时间向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11575970/

相关文章:

r - 让 S4 对象充当 S3 类?

r - 将表达式传递到 `MoreArgs` 的 `mapply`

linux - 为什么系统时间0在这里?

r - 在 R 中计算省略重叠日期的持续时间

r - 在 `df1` 中创建一个变量,具体取决于 `df1` (`df1$var1` 的一个变量,以及 `df2` 的一个可根据 `df1$var1` 更改的变量

r - 将 ymd_hms 时间映射到 15 分钟的时间间隔

python - 在R中制作时间序列数据框

r - 为相同的向量组合获取不同的相关值

macos - 如何加速/减慢应用程序的 'time'

jquery - 使用 jQuery animate 设置间隔计数器