Applying functions to rolling windows

Manipulating Time Series Data in R

Harrison Brown

Graduate Researcher in Geography

Rolling functions from zoo

zoo::roll*:

  • rollmean()
  • rollmax()
  • rollsum()
  • ...

Limitations:

  • No rollmin()!
  • Only certain functions exist
Manipulating Time Series Data in R

rollapply

rollapply(data = ftse,
          width = 7,
          FUN = min,
          align = 'right',
          fill = NA)

Arguments:

  • data: Time series object
  • width: Width of window (k)
  • FUN: Summary function (mean, max, ...)
  • align: Window alignment ('left', 'right', or 'center')
  • fill: Values to fill in outside of window
Manipulating Time Series Data in R

Roll-applying functions

Goal:

  • Find range of values within 30-day window
  • Approximate 'variation' in data
daily_temp
2019-01-01 13.191304
2019-01-02  6.945833
2019-01-03  8.495833
2019-01-04  8.683333
2019-01-05  7.400000
...
find_range <- function(x){
  max(x) - min(x)
}
daily_temp_range <- 
  rollapply(
      daily_temp,
    FUN = find_range,
    width = 30,
    align = 'right',
    fill = NA
  )
Manipulating Time Series Data in R

Roll-applying functions

autoplot(daily_temp_range) + 
  theme_light() + 
  labs(y = 'Temperature Range')

Plot of the 'daily temperature range' time series. This plot shows how the range of values changes across time; a range is calculated for a 30-day rolling window, and the difference between the minimum and maximum values is reported in the plot.

Manipulating Time Series Data in R

Let's practice!

Manipulating Time Series Data in R

Preparing Video For Download...