2015-10-14 19 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

相關問題