2

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

このような平日の時間範囲の明確な関数定義があれば、さらに良いです。夕方のラッシュアワーと、ラッシュアワーではなく、最終的にこれらのどれでもない昼間もあるためです!

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 に答える