15

Rの日付を任意のレベルの精度でグループ化しようとしています。

例を使用して、これを最も近い時間または分に行うのは非常に簡単ですlubridate

library(lubridate)
nearest_hour = floor_date(now(), 'hour')

次に、そのような日付のリストを単純なsummarise ddplyfromなどでグループ化できplyrます。

私がやりたいのは、任意の精度で日付を丸めることです。たとえば、最も近い 15 分または 3 時間ごとに丸めます。

nearest_three_hours = floor_date(now(), '3 hours')

http://r.789695.n4.nabble.com/Truncating-dates-and-other-date-time-manipulations-td866901.htmlでそのようなことについての議論がありますが、日付を切り取る以外にはないようです解決済みです。

4

4 に答える 4

5

lubridateライブラリに基づいて、これを試すことができます

library(lubridate)
round_minute<-function(x,precision){
  m<-minute(x)+second(x)/60
  m.r<- round(m/precision)*precision
  minute(x)<-m.r
  second(x)<-0
  x
}

round_minute(ymd_hms(c("2013-06-03 22:53:00","2013-05-03 12:18:00","2013-05-03 00:10:00")),15)

> "2013-06-03 23:00:00 UTC" "2013-05-03 12:15:00 UTC" "2013-05-03 00:15:00 UTC"

のおかげで、コードはすべてのトリッキーな状況をうまく処理しlubridateます。もちろん、この関数は分単位で表される精度に対してのみ機能しますが、他の単位に簡単に拡張でき、本当に必要な場合は汎用関数を作成することもできます。

于 2013-09-25T06:58:30.703 に答える
5

最も近い原子単位にすでに床を潤滑します。床を最も近い15分にするには、これはあなたがやりたいことだと思います(丸めません)。findIntervalと定義された一連のブレークポイントを介して正しい範囲にマップするだけです。この floor_time を試してみてください。これは機能的には floor_date と同等ですが、秒、分、または時間単位の変数を指定できます。

floor_time <- function(x, k = 1, unit = c("second", "minute", "hour", "day", 
                                          "week", "month", "year")) {
  require(lubridate)

  nmax <- NULL

  switch(unit, second = {nmax <- 60},
         minute = {nmax <- 60},
         hour = {nmax <- 24})

  cuts <- seq(from = 0, to = nmax - 1, by = k)
  new <- switch(unit, 
                second = update(x, seconds = cuts[findInterval(second(x), cuts)]), 
                minute = update(x, minutes = cuts[findInterval(minute(x), cuts)], 
                                seconds = 0), 
                hour = update(x, hours = cuts[findInterval(hour(x), cuts)], 
                              minutes = 0, seconds = 0), 
                day = update(x, hours = 0, minutes = 0, seconds = 0), 
                week = update(x, wdays = 1, hours = 0, minutes = 0, seconds = 0), 
                month = update(x, mdays = 1, hours = 0, minutes = 0, seconds = 0), 
                year = update(x, ydays = 1, hours = 0, minutes = 0, seconds = 0))

  new
}
于 2014-04-19T03:06:05.730 に答える
5

lubridateはより一般的なround_date()機能を持つようになりました。

lubridate::round_date(date, "5 mins")
lubridate::round_date(date, "2 hours")
于 2017-07-13T16:19:57.070 に答える