How to perform Rolling Average in R
How to perform Rolling Average in R, A rolling average in time series analysis represents the average value over a predetermined number of prior periods.
Using the rollmean() function from the zoo package in R is the simplest approach to compute a rolling average:
library(dplyr) library(zoo)
Calculate the 3-day rolling average
df %>% mutate(rolling_avg = rollmean(values, k=3, fill=NA, align='right'))
For the column labeled values, this particular example computes a 3-day rolling average.
How to use this function is explained in the example that follows.
How to perform Rolling Average in R
Let’s say we have the following R data frame, which displays sales of a certain product over a period of 10 days:
Let’s create a data frame
df <- data.frame(day=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â sales=c(215, 120, 114, 116, 217, 120, 112, 115, 114, 191))
df day sales 1Â Â Â 1Â Â 215 2Â Â Â 2Â Â 120 3Â Â Â 3Â Â 114 4Â Â Â 4Â Â 116 5Â Â Â 5Â Â 217 6Â Â Â 6Â Â 120 7Â Â Â 7Â Â 112 8Â Â Â 8Â Â 115 9Â Â Â 9Â Â 114 10Â 10Â Â 191
For each row of the data frame, we can add a new column called avg_sales3 that shows the rolling average of sales for the preceding three days:
library(dplyr) library(zoo)
Now calculate 3-day rolling average of sales
df %>% Â mutate(avg_sales3 = rollmean(sales, k=3, fill=NA, align='right'))
day sales avg_sales3 1Â Â Â 1Â Â 215Â Â Â Â Â Â Â Â NA 2Â Â Â 2Â Â 120Â Â Â Â Â Â Â Â NA 3Â Â Â 3Â Â 114Â Â 149.6667 4Â Â Â 4Â Â 116Â Â 116.6667 5Â Â Â 5Â Â 217Â Â 149.0000 6Â Â Â 6Â Â 120Â Â 151.0000 7Â Â Â 7Â Â 112Â Â 149.6667 8Â Â Â 8Â Â 115Â Â 115.6667 9Â Â Â 9Â Â 114Â Â 113.6667 10Â 10Â Â 191Â Â 140.0000
The quantity of prior periods used to generate the rolling average is controlled by the value of the k parameter in the rollmean() function.
The rolling average of the sales figure for the preceding three periods is displayed in the avg_sales3 column.
For instance, the first result of 149.6667 is determined as follows:
3-Day Moving Average is equal to 149.6667 (215 + 120 + 114) / 3.
The modify() function’s multiple rollmean() capabilities can be used to perform numerous rolling average calculations simultaneously.
The code below, for instance, demonstrates how to compute the 3-day and 4-day moving averages of sales:
ggplot2 scale in R (grammar for graphics) »