2012-07-20 2 views
2

POSIXlt 시간의 벡터가 아침 러시 아워에있는 경우 TRUE/FALSE를 반환하도록 R에서 정리 함수를 만들려고합니다. 월요일 오전 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을 사용하는 것보다 더 간단한 방법을 사용합니다.

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

매우 깔끔한 당신은 다음 (base 기능 사용) 할 수있다! 이 값은 단일 값 (예 : 함수 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

+1

나는 당신의 벡터를 가지고 시험해 보았고 완벽하게 잘 작동했다. 'difftime'에서'tz' 인자로 시도 했습니까? – plannapus

+0

예 tz = 'UTC'를 입력하면 올바르게 작동합니다. – Sean