Day 07: slider::slide()

Do window-based computations, like rolling averages and cumulative sums, by “sliding” across your data with slider::slide() and friends.

Published

December 7, 2022

The slider package provides “sliding window” functions that let you iterate over windows of your data to compute things like rolling averages and cumulative sums (Vaughan 2022).

slide() is similar to purrr::map(), but instead of applying a function, .f, to each element of its input, .x, it applies the function to each window of .x, returning a list of the same length as the input.1

The windows are most easily defined using the .before and/or .after arguments, which can also be set to Inf should you want your window to be ever expanding.

Let’s take a look a a simple example, calculating the mean for each element of a vector with a window that includes one value before.

library(slider)
our_vec <- c(2:5)
slide(our_vec, mean, .before = 1)
[[1]]
[1] 2

[[2]]
[1] 2.5

[[3]]
[1] 3.5

[[4]]
[1] 4.5

Note that the value returned for our first element, above, is the same as that element (2). This is because it has no values before it, and slide()’s default behavior is to compute on incomplete windows. You can use the complete argument to tell slide() to only compute on complete windows.

slide(our_vec, mean, .before = 1, .complete = TRUE)
[[1]]
NULL

[[2]]
[1] 2.5

[[3]]
[1] 3.5

[[4]]
[1] 4.5

As mentioned, you can set .before to Inf to do an expanding window computation (meaning that it includes everything that came before it).

slide(our_vec, mean, .before = Inf)
[[1]]
[1] 2

[[2]]
[1] 2.5

[[3]]
[1] 3

[[4]]
[1] 3.5

Learn more

In addition to slide(), slider has two other core functions, slide_index() (which allows you to do a rolling computation relative to an index), and slide_period() (which lets you break up an index into chunks by periods, such as months). You can learn more about all three of these functions in the introductory vignette, Getting started with slider.

Want to fit this into a row-oriented workflow? See Row-wise iteration with slider.

Wondering how slide() fits in with the tsibble package (Wang, Cook, and Hyndman 2020) from whence it came? Then Converting from tsibble is the vignette for you.

Davis Vaughan (the author of slider) also gave a 5-minute lightning talk, Sliding Windows and Calendars, at rstudio::conf(2020) on using slider with the almanac package—particularly handy if you’ve got a time series with missing data.

References

Vaughan, Davis. 2022. slider: Sliding Window Functions. https://slider.r-lib.org.
Wang, Earo, Dianne Cook, and Rob J Hyndman. 2020. “A New Tidy Data Structure to Support Exploration and Modeling of Temporal Data.” Journal of Computational and Graphical Statistics 29 (3): 466–78. https://doi.org/10.1080/10618600.2019.1695624.