Short examples for moving average and cumulative average usig R.
Moving average
Some alternatives to do moving average, sometimes called running mean or rolling mean. You can use base R, data.table or zoo package.
Use function frollmean from data.table package or rollmean from zoo package.
Example of using frollmean can be seen here.
library(data.table)
d = as.data.table(list(1:6/2, 3:8/4))
V1 V2
1: 0.5 0.75
2: 1.0 1.00
3: 1.5 1.25
4: 2.0 1.50
5: 2.5 1.75
6: 3.0 2.00
## rollmean of single vector and single window
frollmean(d[, V1], 3)
[1] NA NA 1.0 1.5 2.0 2.5
## multiple columns at once
frollmean(d, 3)
## multiple windows at once
frollmean(d[, .(V1)], c(3, 4))
## multiple columns and multiple windows at once
frollmean(d, c(3, 4))
## three above are embarrassingly parallel using openmp
With base R, you can use filter as proposed here.
ma <- function(x, n = 5){stats::filter(x, rep(1 / n, n), sides = 2)}
This function using moving average of 5 values ie. n = 5 and allocates the result to the center of these 5 values ie. slides = 2. This is simlar to using align in data.table::frollmean or zoo:rollmean. The example of the different alignment can be seen here.
means <- sapply(c("right","center","left"),
function(x)data.table::frollmean(d[, V1],3,align = x))
cbind(d, means)
V1 V2 right center left
1: 0.5 0.75 NA NA 1.0
2: 1.0 1.00 NA 1.0 1.5
3: 1.5 1.25 1.0 1.5 2.0
4: 2.0 1.50 1.5 2.0 2.5
5: 2.5 1.75 2.0 2.5 NA
6: 3.0 2.00 2.5 NA NA
Cumulative average
Function cumsum and seq_along can be used from base R but be careful to check that there isn’t any NA in the dataset. Example of using it as follows:
data <- c(2, 5, 7, 9, 12)
ds <- cumsum(data)
ds/seq_along(data)
The result will give a cumulative of the first 1 value cumulative average, then the first 2 values, the first 3 values etc.