我在使用时Date
或IDate
在使用时分配一个新列by =
。它正在创建一个整数列,而不是Date
预期的。
require(data.table)
dt <- data.table(date = as.IDate(sample(10000:11000, 10),
origin = "1970-01-01"))
dt[, group := rep(1:2, 5)]
print(dt)
# date group
# 1: 1997-06-12 1
# 2: 1998-02-19 2
# 3: 1998-04-25 1
# 4: 1998-01-27 2
# 5: 1997-10-29 1
# 6: 1998-05-08 2
# 7: 1999-05-09 1
# 8: 1999-06-26 2
# 9: 1997-11-01 1
# 10: 1997-07-19 2
这有效:
dt[, min.date := min(date)]
print(dt)
# date group min.date
# 1: 1997-06-12 1 1997-06-12
# 2: 1998-02-19 2 1997-06-12
# 3: 1998-04-25 1 1997-06-12
# 4: 1998-01-27 2 1997-06-12
# 5: 1997-10-29 1 1997-06-12
# 6: 1998-05-08 2 1997-06-12
# 7: 1999-05-09 1 1997-06-12
# 8: 1999-06-26 2 1997-06-12
# 9: 1997-11-01 1 1997-06-12
# 10: 1997-07-19 2 1997-06-12
但问题是:
dt[, min.group.date := as.IDate(min(date)), by = group]
print(dt)
# date group min.date min.group.date
# 1: 1997-06-12 1 1997-06-12 10024
# 2: 1998-02-19 2 1997-06-12 10061
# 3: 1998-04-25 1 1997-06-12 10024
# 4: 1998-01-27 2 1997-06-12 10061
# 5: 1997-10-29 1 1997-06-12 10024
# 6: 1998-05-08 2 1997-06-12 10061
# 7: 1999-05-09 1 1997-06-12 10024
# 8: 1999-06-26 2 1997-06-12 10061
# 9: 1997-11-01 1 1997-06-12 10024
# 10: 1997-07-19 2 1997-06-12 10061
min.group.date
是数字而不是Date
.
dt[, class(min.group.date)]
# [1] "numeric"
如果我将列初始化为Date
or IDate
,它将按预期工作:
dt <- data.table(date = as.IDate(sample(10000:11000, 10), origin = "1970-01-01"))
dt[, group := rep(1:2, 5)]
dt[, min.group.date := as.IDate(NA)]
dt[, min.group.date := min(date), by = group]
dt[, class(min.group.date)]
# [1] "IDate" "Date"