r-lib / clock

A Date-Time Library for R
https://clock.r-lib.org
Other
97 stars 4 forks source link

Recycling in `Date-arithmetic` and `posixt-arithmetic` #313

Closed Henrik-P closed 1 year ago

Henrik-P commented 1 year ago

From Details in ?Date-arithmetic and ?posixt-arithmetic:

x and n are recycled against each other.

However, this does not seem to be the case. A small example where I would expect recycling to work, x of length 2 and n of length 4:

Date arithmetics:

library(clock)
library(lubridate)
x = as.Date(c("2015-12-31", "2022-11-30"))
n = c(1L, 1L, 2L, 2L)

add_years(x, n)
add_quarters(x, n)
add_months(x, n) # possibly using invalid = "previous"
# Error in `year_month_day_plus_duration()`:
# ! Can't recycle `x` (size 2) to match `n` (size 4).

add_weeks(x, n)
add_days(x, n)
# Error in `duration_arith()`:
# ! Can't recycle `x` (size 2) to match `y` (size 4).`

# recycling works with comparable lubridate code, e.g.
x %m+% months(n)
# [1] "2016-01-31" "2022-12-30" "2016-02-29" "2023-01-30" 

POSIXct arithmetics

x = as.POSIXct(c("2015-12-31 09:15:30", "2022-11-30 09:15:30"))

add_years(x, n)
add_months(x, n)
# Error in `year_month_day_plus_duration()`:
# ! Can't recycle `x` (size 2) to match `n` (size 4).

add_hours(x, n)
# Error in `duration_arith()`:
# ! Can't recycle `x` (size 2) to match `y` (size 4).

# similar for the other `add_xxx`

# recycling works with comparable lubridate code, e.g.
x %m+% months(n)

Thanks for your great work!

Henrik-P commented 1 year ago

Presumably the answer by @trevorld at my other, similar issue applies here as well.

DavisVaughan commented 1 year ago

Tracking in https://github.com/r-lib/clock/issues/314#issuecomment-1427129530