我在difftime值的data.table中有一列,单位设置为天。我正在尝试使用
创建另一个data.table汇总值dt2 <- dt[, .(AvgTime = mean(DiffTime)), by = Group]
打印新的data.table时,我会看到
等值1.925988e+00 days
1.143287e+00 days
1.453975e+01 days
我想仅限制此列的小数位值(即不设置options()
,除非我可以通过这种方式专门针对difftime值执行此操作)。当我尝试使用上面的方法,修改,例如
dt2 <- dt[, .(AvgTime = round(mean(DiffTime)), 2), by = Group]
我留下NA值,基本round()
和format()
函数都会返回警告:
平均值(DiffTime):参数不是数字或逻辑。
奇怪的是,如果我在数字字段上执行相同的操作,则运行没有问题。此外,如果我运行两行独立的代码,我可以完成我想要做的事情:
dt2 <- dt[, .(AvgTime = mean(DiffTime)), by = Group]
dt2[, AvgTime := round(AvgTime, 2)]
library(data.table)
set.seed(1)
dt <- data.table(
Date1 =
sample(seq(as.Date('2017/10/01'),
as.Date('2017/10/31'),
by="days"), 24, replace = FALSE) +
abs(rnorm(24)) / 10,
Date2 =
sample(seq(as.Date('2017/10/01'),
as.Date('2017/10/31'),
by="days"), 24, replace = FALSE) +
abs(rnorm(24)) / 10,
Num1 =
abs(rnorm(24)) * 10,
Group =
rep(LETTERS[1:4], each=6)
)
dt[, DiffTime := abs(difftime(Date1, Date2, units = 'days'))]
# Warnings/NA:
class(dt$DiffTime) # "difftime"
dt2 <- dt[, .(AvgTime = round(mean(DiffTime), 2)), by = .(Group)]
# Works when numeric/not difftime:
class(dt$Num1) # "numeric"
dt2 <- dt[, .(AvgNum = round(mean(Num1), 2)), by = .(Group)]
# Works, but takes an additional step:
dt2<-dt[,.(AvgTime = mean(DiffTime)), by = .(Group)]
dt2[,AvgTime := round(AvgTime,2)]
# Works with base::mean:
class(dt$DiffTime) # "difftime"
dt2 <- dt[, .(AvgTime = round(base::mean(DiffTime), 2)), by = .(Group)]
当课程为difftime
时,为什么我无法在一步中完成此转换(平均值的四舍五入)?我在执行中遗漏了什么吗?这是data.table
中的某种错误,它无法正确处理difftime
?
在github上添加了问题。
答案 0 :(得分:3)
此问题已通过2019年5月15日的更新Very abstract example of Mertens exposure fusion algorithm here,data {table版本#3567已发布1.12.4
修复。答案 1 :(得分:0)
这可能会有点晚,但是如果您真的希望它可以工作,您可以这样做:
as.numeric(round(as.difftime(difftime(DATE1, DATE2)), 0))