在data.table中舍入POSIXct

时间:2014-08-13 18:15:42

标签: r data.table posixct

使用this question中的相同数据,在data.table v1.9.2中将日期时间舍入到第二个时出现问题。

require(data.table)
options(digits.secs=3)  # usually placed in .Rprofile
DT <- data.table(timestamp=c(as.POSIXct("2013-01-01 17:51:00.707"),
                             as.POSIXct("2013-01-01 17:51:59.996"),
                             as.POSIXct("2013-01-01 17:52:00.059"),
                             as.POSIXct("2013-01-01 17:54:23.901"),
                             as.POSIXct("2013-01-01 17:54:23.914")))
DT
DT[ , round(timestamp)]  # looks good
DT[ , timestamp_rounded := round(timestamp)]  # does not work
DT[ , timestamp_rounded := round(timestamp, units="secs")]  # does not work
DT
#                   timestamp timestamp_rounded
# 1: 2013-01-01 17:51:00.707       1,0,0,24,24
# 2: 2013-01-01 17:51:59.996    51,52,52,54,54
# 3: 2013-01-01 17:52:00.059    17,17,17,17,17
# 4: 2013-01-01 17:54:23.901         1,1,1,1,1
# 5: 2013-01-01 17:54:23.914         0,0,0,0,0

我找到了使用lubridate的解决方案:

require(lubridate)
DT[ , timestamp_rounded := round_date(timestamp, "second")]  # works

是否有data.table方法?

1 个答案:

答案 0 :(得分:5)

round.POSIXt生成POSIXlt个对象,data.table(故意)不存储POSIXlt个对象,因为它们不必要地大。然后解决方案就是简单地转换回POSIXct

DT[, timestamp_rounded := as.POSIXct(round(timestamp))]
#                 timestamp   timestamp_rounded
#1: 2013-01-01 17:51:00.707 2013-01-01 17:51:01
#2: 2013-01-01 17:51:59.996 2013-01-01 17:52:00
#3: 2013-01-01 17:52:00.059 2013-01-01 17:52:00
#4: 2013-01-01 17:54:23.901 2013-01-01 17:54:24
#5: 2013-01-01 17:54:23.914 2013-01-01 17:54:24