I’m trying to create a clean function in R to return TRUE/FALSE if a vector of POSIXlt times are in morning rush hour, i.e. 7.30am to 9.30am Monday to Friday. This is what I’ve done so far, but it seems a bit long and convoluted. Is it possible to improve on this while keeping the code itself readable?
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))
Even better if there is a clean function definition for weekday time ranges like this, as I also have evening rush hour, and daytime which is not rush hour and finally not any of these!
I would do something way simpler than that using
difftimeandcut. You can do the following (usingbasefunctions):Edit: You can also add a time-zone parameter to
difftimeif needed: