【问题标题】:Rounding POSIXct in data.table在 data.table 中舍入 POSIXct
【发布时间】:2014-08-13 18:15:41
【问题描述】:

使用来自 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 方法吗?

【问题讨论】:

  • “是否有 data.table 方法”是什么意思?您正在使用 data.table 不是吗?
  • 这并不能完全回答您的问题,但 data.table 包中的 IDateTime 可能会有所帮助。

标签: r data.table posixct


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-04-16
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2017-03-23
    • 2015-08-10
    相关资源
    最近更新 更多