POSIXlt 時間のベクトルが朝のラッシュアワー、つまり月曜日から金曜日の午前 7 時 30 分から午前 9 時 30 分にある場合に TRUE/FALSE を返すクリーンな関数を 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))
このような平日の時間範囲の明確な関数定義があれば、さらに良いです。夕方のラッシュアワーと、ラッシュアワーではなく、最終的にこれらのどれでもない昼間もあるためです!