rolling applies a funtion (FUN) over a moving window (see .width and .direction) for each element of x using zoo::rollapply().
Usage
rolling(
x,
FUN = mean,
...,
.width = 3,
.direction = "backward",
.fill = NA,
.min_non_na = 0
)Arguments
- x
A vector.
- FUN
A function to be applied to each window of
x. If is a character string, it will be converted to a function usingget(), unless it is in "sum", "mean", "min", or "max" which have built-in vectorized (faster) implementations. Default is"mean".- ...
Additional arguments to be passed to
FUN.- .width
A numeric value indicating the width of the window. See
zoo::rollapply()for more details. Default is3.- .direction
A character string or numeric value indicating the direction of the window. Options are
"backward"(1),"forward"(-1), or"center"(0). See thealignargument inzoo::rollapply()for more details. Default is"backward".- .fill
(Optional) A single value to be used for filling in any values that are outside of the window. See
zoo::rollapply()for more details. Default isNA.- .min_non_na
(Optional) A single numeric value indicating the minimum number of observations required to compute a value. Default is
0.
Details
Be sure to fill any gaps in
xand ensurexis sorted, otherwise the window may be applied incorrectly.Values outside of the window are replaced with
.fill..min_non_nais passed todo_if_enough()to only applyFUNif enough values are present in the window.
Examples
x <- c(1, 2, 3, 4, 5)
x |> rolling(mean, .width = 2)
#> [1] NA 1.5 2.5 3.5 4.5
x |> rolling(mean, .width = 2, .direction = "forward", .fill = -1)
#> [1] 1.5 2.5 3.5 4.5 -1.0