Search code examples
rdatetimeposixct

Vector of dates inconsistent length after rounding in R


I need both the original and a rounded-to-the-day version of a datetime in a data.table. When I use the base round function to do this (as recommended here), I start getting errors regarding the number of items when I try to add it back into my data.table - even though the length looks right.

Example:

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)

When run, produces:

> 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

What's going wrong and how do I fix it?


Solution

  • ?round.POSIXt reveals that in this case, round() returns a POSIXlt object. But data.table doesn't work with those. So just do

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

    and you're fine.