The functions adds moving average for an arbitrary number of intervals. The data can be returned sorted or according to the original order.

moving_average(x, x_order, interval, na.rm = FALSE)

Arguments

x

A vector used to calculate moving average.

x_order

A vector used for sorting of x defaults to sort(x).

interval

A number of intervals for moving average, defaults to round(length(x) / 3, 0).

na.rm

As in sum, defaults to FALSE.

Value

A vector of length equivalent to x with NA for n < interval as in x[n].

Details

The function can be used independently or within dplyr pipeline.

Examples

moving_average(x = sample(1:100, 10), x_order = 10:1)
#> [1] NA NA 53.33333 54.00000 65.33333 73.33333 60.66667 61.66667 #> [9] 59.00000 57.00000