r-lib / slider

Sliding Window Functions
https://slider.r-lib.org
Other
295 stars 12 forks source link

Implement `slider_plus()` and `slider_minus()` #184

Closed DavisVaughan closed 1 year ago

DavisVaughan commented 1 year ago

Closes #91

It is going to be too hard to move to vec_arith() and ensure that we are 100% backwards compatible with the original + and - implementations. Instead, we provide a double dispatch entry point where packages like clock and almanac can inject special behavior with their types when + and - don't work properly

library(slider)
library(clock)

i <- as.Date("2019-01-01") + 0:5
x <- seq_along(i)

# Doesn't work. But clock has `vec_arith()` methods for this!
slide_index(x, i, identity, .before = duration_days(2))
#> Warning in fn_default(x, y): Incompatible methods ("-.Date", "-.vctrs_vctr") for
#> "-"
#> Error in x - y: non-numeric argument to binary operator

# So clock can register this double dispatch method:
slider_minus.Date.clock_duration <- function(x, y) {
  vctrs::vec_arith("-", x, y)
}

slide_index(x, i, identity, .before = duration_days(2))
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 1 2
#> 
#> [[3]]
#> [1] 1 2 3
#> 
#> [[4]]
#> [1] 2 3 4
#> 
#> [[5]]
#> [1] 3 4 5
#> 
#> [[6]]
#> [1] 4 5 6

Created on 2022-11-09 with reprex v2.0.2.9000