【问题标题】:Vector of dates inconsistent length after rounding in RR中舍入后日期长度不一致的向量
【发布时间】:2021-04-27 16:14:02
【问题描述】:

我需要 data.table 中日期时间的原始版本和按日取整的版本。当我使用 base round 函数执行此操作时(推荐 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

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

【问题讨论】:

  • 看起来像 data.table 的东西。如果您执行temp &lt;- as.data.frame(temp) 并运行您的代码,它工作正常。确实:(a)class(dates_form3) 表明round() 返回了一个 POSIXlt 对象,而这个问题 (stackoverflow.com/questions/67286833/…) 表明 data.table 不喜欢 POSIXlt。在dates_form3 上使用as.POSIXct,你会没事的。

标签: r datetime posixct


【解决方案1】:

?round.POSIXt 表明在这种情况下,round() 返回一个 POSIXlt 对象。但是data.table doesn'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)

你很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2023-04-09
    相关资源
    最近更新 更多