Calculate Moving Average, Maximum, Median & Sum of Time Series in R (6 Examples)

 

This tutorial shows how to calculate moving averages, maxima, medians, and sums in the R programming language.

The article looks as follows:

Let’s dive right into the examples!

 

Creation of Example Data

We’ll use the following data as basement for this R programming tutorial:

set.seed(98234)                                    # Creating example series
my_series <- 1:100 + rnorm(100, 0, 10)
my_series                                          # Printing series
# -19.1265321  -4.2533086  13.8434357  -1.6570237  18.6339137   3.7275765  ...

Have a look at the previous output of the RStudio console. It shows that our example data is a series of numeric values with a length of 100. In a real application, this could be a time series.

 

Example 1: Compute Moving Average Using User-Defined Function

In Example 1, I’ll explain how to create a user-defined function to calculate a moving average (also called rolling average or running average) in R.

We can create a new function called moving_average as shown below (credit to Matti Pastell’s response in this thread):

moving_average <- function(x, n = 5) {             # Create user-defined function
  stats::filter(x, rep(1 / n, n), sides = 2)
}

Now, we can apply this function to our time series data:

my_moving_average_1 <- moving_average(my_series)   # Apply user-defined function
my_moving_average_1                                # Printing moving average
#         NA         NA   1.488097   6.058919   7.348637   5.377346   7.715196   4.944003  ...

The output are the moving averages of our time series.

 

Example 2: Compute Moving Average Using rollmean() Function of zoo Package

In case you don’t want to create your own function to compute rolling averages, this example is for you. Example 2 shows how to use the zoo package to calculate a moving average in R.

If we want to use the functions of the zoo package, we first need to install and load zoo:

install.packages("zoo")                            # Install zoo package
library("zoo")                                     # Load zoo

Now, we can use the rollmean function of the zoo package to calculate our running mean:

my_moving_average_2 <- rollmean(my_series, k = 5)  # Apply rollmean function
my_moving_average_2                                # Printing moving average
# 1.488097   6.058919   7.348637   5.377346   7.715196   4.944003  ...

The output values are the same as in Example 1 (without the NA values at the beginning and at the end of the output vector).

 

Example 3: Compute Moving Maximum Using rollmax() Function of zoo Package

The following R programming code illustrates how to use the rollmax function of the zoo package to calculate the moving maximum in R.

my_moving_max <- rollmax(my_series, k = 5)         # Apply rollmax function
my_moving_max                                      # Printing moving maximum
# 18.63391  18.63391  18.63391  18.63391  18.63391  10.03223  31.52406  ...

 

Example 4: Compute Moving Median Using rollmedian() Function of zoo Package

The R programming code below illustrates how to use the rollmedian function of the zoo package to return the moving median to the RStudio console.

my_moving_median <- rollmedian(my_series, k = 5)   # Apply rollmedian function
my_moving_median                                   # Printing moving median
# -1.657024   3.727576   3.727576   3.727576   3.986984   3.986984   4.777944 ...

 

Example 5: Compute Moving Sum Using rollsum() Function of zoo Package

In this Example, I’ll illustrate how to apply the rollsum function of the zoo package to calculate the rolling sum in R.

my_moving_sum <- rollsum(my_series, k = 5)         # Apply rollsum function
my_moving_sum                                      # Printing moving sum
# 7.440485  30.294594  36.743183  26.886731  38.575982  24.720013  52.516494 ...

 

Example 6: Draw Plot of Time Series, Moving Average, Maximum, Median & Sum

In the previous examples, I have explained how to compute different moving metrics in R. This Example explains how to draw all these values to a graphic.

plot(1:length(my_series), my_series, type = "l",   # Plotting series & moving metrics
     ylim = c(min(my_series), max(my_moving_sum)),
     xlab = "Time Series", ylab = "Values")
lines(1:length(my_series), c(NA, NA, my_moving_average_2, NA, NA), type = "l", col = 2)
lines(1:length(my_series), c(NA, NA, my_moving_max, NA, NA), type = "l", col = 3)
lines(1:length(my_series), c(NA, NA, my_moving_median, NA, NA), type = "l", col = 4)
lines(1:length(my_series), c(NA, NA, my_moving_sum, NA, NA), type = "l", col = 5)
legend("topleft",
       c("Time Series", "Moving Average", "Moving Maximum", "Moving Median", "Moving Sum"),
       lty = 1, col = 1:5)

 

r graph figure 1 moving average maximum median sum time series r

 

Figure 1 shows the output of the previous R programming syntax: A plot showing the different moving metrics.

 

Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. I explain the topics of this tutorial in the video:

 

 

In addition, you might want to have a look at the related articles on this website. A selection of tutorials is shown below:

 

Summary: This post illustrated simple ways on how to compute moving averages, maxima, medians, and sums in the R programming language. Don’t hesitate to let me know in the comments, in case you have any further questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top