I'm learning the R package lubridate. I discovered that the round_date() function does not provide the correct answer when the input is a date. The input must be a datetime. floor_date() and ceiling_date() have no such problem.
For example,
date1 <- as_datetime("2022-09-23")
date2 <- as_datetime("2022-05-19")
round_date(date1, "year")
#> [1] "2023-01-01 UTC"
round_date(date2, "year")
#> [1] "2022-01-01 UTC"
Hello @lesoch ,
the documentation (?lubridate::round_date) explicitly mentions that the first argument has to be a date-time object. However at the end of the docs it also mentions Rounding Up Date Objects.
The variables date3 and date4 have class Date.
Looking in the code (displaying lubridate::round_date) I see that internally the variables above , mid and below are created. In your case the mid variable is not in the range between below and above . I suspect that this is not correct and that the assignment for mid should read:
mid <- unclass(as.POSIXct(x))
So you are right that the function does not perform as you had expected.
The (easy) solution: always transform your variables with as_datetime before rounding:
Thanks for your quick reply. I have no issue with using datetime instead of date. What puzzled me as a R beginner is its inconsistency with floor_date() and ceiling_date() which work correctly with date input.