Round time at X hours in R?

Performing modeling predictions based on time data, I want to write a function in R (possibly using data.table), which rounds the date by X the number of hours. For instance. rounding for 2 hours should give the following:

"2014-12-28 22:59:00 EDT" becomes "2014-12-28 22:00:00 EDT" 
"2014-12-28 23:01:00 EDT" becomes "2014-12-29 00:00:00 EDT" 

This is very easy to do when you twist for 1 hour - using the function round.POSIXt(.date, "hour").
Writing a generic function, as I do below using a few operators if, becomes pretty ugly:

d7.dateRoundByHour <- function (.date, byHours) { 

  if (byHours == 1)
    return (round.POSIXt(.date, "hour"))

  hh = hour(.date); dd = mday(.date); mm = month(.date); yy = year(.date)    
  hh = round(hh/byHours,digits=0) * byHours
  if (hh>=24) { 
    hh=0; dd=dd+1 
  }
  if ((mm==2 & dd==28) | 
      (mm %in% c(1,3,5,7,8,10,12) & dd==31) | 
      (mm %in% c(2,4,6,9,11) & dd==30)) {  # NB: it won't work on 29 Feb leap year. 
    dd=1; mm=mm+1
  }
  if (mm==13) {
    mm=1; yy=yy+1
  }
  str = sprintf("%i-%02.0f-%02.0f %02.0f:%02.0f:%02.0f EDT", yy,mm,dd, hh,0,0)
  as.POSIXct(str, format="%Y-%m-%d %H:%M:%S") 
}

Can anyone show a better way to do this?
(perhaps by converting to numeric and back to POSIXt or some other POSIXt functions?)

+4
source share
2

round_date lubridate. , date, :

dt[, date := round_date(date, '2 hours')]

, :

x <- as.POSIXct("2014-12-28 22:59:00 EDT")
round_date(x, '2 hours')
+3

R. " ",

R-:

R> pt <- as.POSIXct(c("2014-12-28 22:59:00", "2014-12-28 23:01:00 EDT"))
R> pt   # just to check
[1] "2014-12-28 22:59:00 CST" "2014-12-28 23:01:00 CST"
R> 
R> scalefactor <- 60*60*2   # 2 hours of 60 minutes times 60 seconds
R> 
R> as.POSIXct(round(as.numeric(pt)/scalefactor) * scalefactor, origin="1970-01-01")
[1] "2014-12-28 22:00:00 CST" "2014-12-29 00:00:00 CST"
R> 

, : POSIXct , , POSIXct.

+3

Source: https://habr.com/ru/post/1670972/


All Articles