早上高峰时间的R测试 - 间隔的时间向量

时间:2012-07-20 08:48:09

标签: 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))

如果工作日时间范围有一个干净的功能定义,那就更好了,因为我也有晚上的高峰时间,白天不是高峰时间,最后也不是这些!

1 个答案:

答案 0 :(得分:2)

我会采用比使用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")