Apply any R function on rolling windows

Dawid Kałędkowski


Using runner

runner package provides functions applied on running windows. The most universal function is runner::runner which gives user possibility to apply any R function f on running windows. Running windows are defined for each data window size k, lag with respect to their indexes. Unlike other available R packages, runner supports any input and output type and also gives full control to manipulate window size and lag/lead.

There are different kinds of running windows and all of them are implemented in runner.

Cumulative windows

The simplest window type which is similar to base::cumsum. At each element window is defined by all elements appearing before current.

In runner this can be achieved as simple by:

Constant sliding windows

Second type of windows are these commonly known as running/rolling/moving/sliding windows. This types of windows moves along the index instead of cumulating like a previous one.
Following diagram illustrates running windows of length k = 4. Each of 15 windows contains 4 elements (except first three).

To obtain constant sliding windows one just needs to specify k argument

Windows depending on date

By default runner calculates on assumption that index increments by one, but sometimes data points in dataset are not equally spaced (missing weekends, holidays, other missings) and thus window size should vary to keep expected time frame. If one specifies idx argument, than running functions are applied on windows depending on date rather on a sequence 1-n. idx should be the same length as x and should be of type Date, POSIXt or integer. Example below illustrates window of size k = 5 lagged by lag = 1. Note that one can specify also k = "5 days" and lag = "day" as in seq.POSIXt.
In the example below in square brackets ranges for each window.

running at

Runner by default returns vector of the same size as x unless one puts any-size vector to at argument. Each element of at is an index on which runner calculates function. Example below illustrates output of runner for at = c(13, 27, 45, 31) which gives windows in ranges enclosed in square brackets. Range for at = 27 is [22, 26] which is not available in current indices.

at can also be specified as interval of the output defined by time interval which results in obtaining results on following indices seq(min(idx), max(idx), by = "<time interval>"). Interval can be set in the same way as in seq.POSIXt function. It’s worth noting that at interval shouldn’t be more frequent than interval of idx - for Date the most frequent interval is a "day", for POSIXt it’s a "sec".

Move and stretch window in time

One can stretch window length by k and shift in time (or index) using lag. Both arguments can be integer and also time interval like for example 2 months. If k or lag are a single value then window size/lag are constant for all elements of x. User can also specify k/lag as vector, then size and lag will vary for each window. Both k and lag can be of length(.) == 1, length(.) == length(x) or length(.) == length(at) (if at is specified). lag can be negative and positive while k only non-negative.

NA padding

Using runner one can also specify na_pad = TRUE which would return NA for any window which is partially out of range - meaning that there is no sufficient number of observations to fill the window. By default na_pad = FALSE, which means that incomplete windows are calculated anyway. na_pad is applied on normal cumulative windows and on windows depending on date. In example below two windows exceed range given by idx so for these windows are empty for na_pad = TRUE. If used sets na_pad = FALSE first window will be empty (no single element within [-2, 3]) and last window will return elements within matching idx.

Using runner with data.frame

User can also put data.frame into x argument and apply functions which involve multiple columns. In example below we calculate beta parameter of lm model on 1, 2, …, n observations respectively. On the plot one can observe how lm parameter adapt with increasing number of observation.

One can also use runner with dplyr also with problematic group_by operations, without need to apply group_modify. Below we apply grouped 20-days beta, by specifying window length k = "10 days" and providing column name where indices (dates) are kept.

When user executes multiple runner calls in dplyr mutate, one can also use run_by function to prespecify arguments in tidyverse pipeline. In the example below runner functions are applied on k = "20 days" calculated on "date" column.

Build-in functions

With runner one can use any R functions, but some of them are optimized for speed reasons. These functions are:
- aggregating functions - length_run, min_run, max_run, minmax_run, sum_run, mean_run, streak_run
- utility functions - fill_run, lag_run, which_run