Ratnanil
Ratnanil

Reputation: 1752

Round hour in timestamp (POSIXct) to the nearest multiple of a certain value in R

I have a date/time value (POSIXct) where I want to round the "hour" value to a multiple of three (00:00, 03:00, 6:00, 9:00, 12:00...).

So far I've extracted the hour as an integer, rounded it accordingly and inserted it back into a POSIXct format. Is there a quicker, more elegant way? This is my code so far:

timestamp <- as.POSIXct("2015-10-14 14:00")
timestamp.h <- as.numeric(format(timestamp, "%H")) + as.numeric(format(timestamp, "%M"))/60
timestamp.h.up <- ceiling(timestamp.h/3)*3
timestamp.up <- as.POSIXct(paste(format(timestamp, "%Y-%m-%d")," ",timestamp.h.up,":00", sep=""))

Upvotes: 0

Views: 235

Answers (1)

mra68
mra68

Reputation: 2960

Conversion to POSIXlt and back to POSIXct is a little bit faster:

f0 <- function( timestamp )
{
  timestamp.h <- as.numeric(format(timestamp, "%H")) + as.numeric(format(timestamp, "%M"))/60
  timestamp.h.up <- ceiling(timestamp.h/3)*3
  timestamp.up <- as.POSIXct(paste(format(timestamp, "%Y-%m-%d")," ",timestamp.h.up,":00", sep=""))
}

f1 <- function( t )
{
  x <- as.POSIXlt(t)
  x[["hour"]] <- 3*ceiling((60*x[["hour"]]+x[["min"]])/180)
  x[["min"]] <- 0

  return(as.POSIXct(x))
}

.

> timestamp <- as.POSIXct("2015-10-14 15:03")

> system.time(
+   for ( i in 1:10000) { t0 <- f0(timestamp) }
+   )
   user  system elapsed 
  16.94    0.00   17.19 

> system.time(
+   for ( i in 1:10000) { t1 <- f1(timestamp) }
+ )
   user  system elapsed 
   2.56    0.00    2.56 

> t0
[1] "2015-10-14 18:00:00 CEST"

> t1
[1] "2015-10-14 18:00:00 CEST"

.

> timestamp <- as.POSIXct("2015-10-14 14:00")

> system.time(
+   for ( i in 1:10000) { t0 <- f0(timestamp) }
+   )
   user  system elapsed 
  14.00    0.00   14.21 

> system.time(
+   for ( i in 1:10000) { t1 <- f1(timestamp) }
+ )
   user  system elapsed 
   1.25    0.00    1.24 

> t0
[1] "2015-10-14 15:00:00 CEST"

> t1
[1] "2015-10-14 15:00:00 CEST"
> 

Upvotes: 1

Related Questions