0

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?

neuropsych
  • 305
  • 3
  • 11
  • 1
    Looks like a `data.table` thing. If you do `temp <- as.data.frame(temp)` and run your code, it works fine. Indeed: (a) `class(dates_form3)` reveals that `round()` has returned a POSIXlt object, and this question (https://stackoverflow.com/questions/67286833/vector-of-dates-inconsistent-length-after-rounding-in-r) reveals that data.table doesn't like POSIXlt. Use `as.POSIXct` on `dates_form3` and you'll be fine. – dash2 Apr 27 '21 at 16:28

1 Answers1

1

?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.

dash2
  • 2,024
  • 6
  • 15