Apply a moving-window variance function to a numeric vector.
roll_var(x, width = 1L, by = 1L, align = c("center", "left", "right"))Numeric vector of the same length as x.
For every index in the incoming vector x, a value is returned that
is the variance of all values in x that fall within a window of width
width.
The align parameter determines the alignment of the return value
within the window. Thus:
align = "left" [*------] will cause the returned vector to have width - 1 NA values at the right end.
align = "center" [---*---] will cause the returned vector to have NA values at either end as needed for centered alignment.
align = "right" [------*] will cause the returned vector to have width - 1 NA values at the left end.
For large vectors, the by parameter can be used to force the window
to jump ahead by indices for the next calculation. Indices that are
skipped over will be assigned NA values so that the return vector still has
the same length as the incoming vector. This can dramatically speed up
calculations for high resolution time series data.
A na.rm argument is not provided for roll_var() because the
statistical meaning of variance computed from partially missing windows may
be ambiguous.
# Example air quality time series
t <- example_pm25$datetime
x <- example_pm25$pm25
x[1:10]
#> [1] 13.032808 9.208778 9.413230 10.089091 10.075755 8.240968 9.507955
#> [8] 10.704980 11.232667 9.767381
roll_var(x, width = 5)[1:10]
#> [1] NA NA 2.3799242 0.5778580 0.5663223 0.8663507 1.3368015
#> [8] 1.3368106 0.5067178 0.3060094