R中舍入后日期长度不一致的向量

Vector of dates inconsistent length after rounding in R

我需要 data.table 中日期时间的原始版本和四舍五入到当天的版本。当我使用基本圆形函数执行此操作时(按照建议 here),当我尝试将它添加回我的 data.table 时,我开始收到有关项目数量的错误 - 即使长度看起来正确.

示例:

temp <- data.table(ID=1:3,dates_unrounded=rep(as.POSIXct(NA),3),dates_rounded=rep(as.POSIXct(NA),3))
dates_form1 <- c("2021-04-01","2021-06-30","2021-05-22")
dates_form2 <- as.POSIXct(dates_form1,format="%Y-%m-%d")
temp$dates_unrounded <- dates_form2
dates_form3 <- round(dates_form2,"days")
temp$dates_rounded <- dates_form3
length(dates_form3)
length(temp$dates_unrounded)

当运行时,产生:

> temp <- data.table(ID=1:3,dates_unrounded=rep(as.POSIXct(NA),3),dates_rounded=rep(as.POSIXct(NA),3))
> dates_form1 <- c("2021-04-01","2021-06-30","2021-05-22")
> dates_form2 <- as.POSIXct(dates_form1,format="%Y-%m-%d")
> temp$dates_unrounded <- dates_form2
> dates_form3 <- round(dates_form2,"days")
> temp$dates_rounded <- dates_form3
Error in set(x, j = name, value = value) : 
  Supplied 11 items to be assigned to 3 items of column 'dates_rounded'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.
> length(dates_form3)
[1] 3
> length(temp$dates_unrounded)
[1] 3

出了什么问题,我该如何解决?

?round.POSIXt 表明在这种情况下,round() returns 是一个 POSIXlt 对象。但是data.tabledoesn't work with those。所以就做

dates_form3 <- round(dates_form2,"days")
dates_form3 <- as.POSIXct(dates_form3)
temp$dates_rounded <- dates_form3
length(dates_form3)
length(temp$dates_unrounded)

你很好。