2

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

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

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

4

1 回答 1

2

我会做一些比使用difftimeand更简单的事情cut。您可以执行以下操作(使用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")
于 2012-07-20T09:20:36.173 回答