2012-07-20 85 views
2

我试图在R中创建一个干净的函数来返回TRUE/FALSE,如果一个POSIXlt时间向量在早晨高峰时间,也就是周一早上7.30到9.30到星期五。这是我迄今为止所做的,但似乎有点漫长而复杂。是否有可能在保持代码本身可读性的同时进行改进?R早晨高峰时间测试 - 时间间隔向量

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

更妙的是,如果有平日时间清洗功能的定义范围喜欢这一点,因为我也有晚高峰时段,和白天这是不急于小时,最后在没有任何这些!

回答

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") 
+0

很整齐!这适用于单个值,例如重命名你的函数mrh1(),mrh1(as.POSIXlt('2012-07-20 07:31:00 UTC')) mrh1(tm)其中tm如上定义 - 与我自己的data.frame(tm,day = wday(tm,label = TRUE,abbr = FALSE),morning.rush.hour(tm),mrh1(tm) ) – Sean 2012-07-20 10:05:05

+1

我试着用你的矢量,它对我来说工作得非常好。你在'difftime'中尝试了'tz'参数吗? – plannapus 2012-07-20 10:56:35

+0

是的,如果我把tz ='UTC' – Sean 2012-07-20 16:32:23