R Compute Moving Average, Median, Maximum & Sum of Time Series (4 Examples)
This article explains how to compute moving averages, maxima, medians, and sums in the R programming language.
Preparing the Examples
x <- c(5, 6, 3, 3, 1, 8, 9, 5, 6, 8) # Create time series x # Print time series to console # 5 6 3 3 1 8 9 5 6 8 |
x <- c(5, 6, 3, 3, 1, 8, 9, 5, 6, 8) # Create time series x # Print time series to console # 5 6 3 3 1 8 9 5 6 8
install.packages("zoo") # Install zoo package library("zoo") # Load zoo package |
install.packages("zoo") # Install zoo package library("zoo") # Load zoo package
Example 1: Moving Average in R
rollmean(x, 3) # Computing moving average # 4.666667 4.000000 2.333333 4.000000 6.000000 7.333333 6.666667 6.333333 |
rollmean(x, 3) # Computing moving average # 4.666667 4.000000 2.333333 4.000000 6.000000 7.333333 6.666667 6.333333
Example 2: Moving Median in R
rollmedian(x, 3) # Computing moving median # 5 3 3 3 8 8 6 6 |
rollmedian(x, 3) # Computing moving median # 5 3 3 3 8 8 6 6
Example 3: Moving Maximum in R
rollmax(x, 3) # Computing moving maximum # 6 6 3 8 9 9 9 8 |
rollmax(x, 3) # Computing moving maximum # 6 6 3 8 9 9 9 8
Example 4: Moving Sum in R
rollsum(x, 3) # Computing moving sum # 14 12 7 12 18 22 20 19 |
rollsum(x, 3) # Computing moving sum # 14 12 7 12 18 22 20 19