2015-10-14 70 views
0

我有一个日期/时间值(POSIXct),我希望将“小时”值舍入为三的倍数(00:00, 03:00,6:00,9:00,12:00)。将时间戳(POSIXct)中的圆整时间调整为R中某个特定值的最接近倍数

到目前为止,我已经提取了小时作为整数,相应地舍入它并将其插回到POSIXct格式。有更快,更优雅的方式吗?这是到目前为止我的代码:

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="")) 
+0

@帕斯卡尔:对不起,我的错。编辑这个问题,它现在应该工作 – Ratnanil

回答

1

转换为POSIXlt和回POSIXct是快一点点:

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" 
> 
+1

这似乎是一个非矢量化的解决方案? – jangorecki