how to moving average in r

To calculate the moving average of a time series data in R, we can use the stats package's filter function.

Assuming data is a time series data in a data frame format, and we want to calculate the 5-day moving average, we can use the following code:

main.r
library(stats)

moving_average <- filter(data$column_name, rep(1/5, 5), sides=2)
81 chars
4 lines

Explanation:

  • data$column_name is the column of the time series we want to calculate the moving average for.
  • rep(1/5, 5) creates a vector of length 5 containing the values of 1/5, which is the weights for the moving average calculation. The weights should add up to 1.
  • sides=2 specifies that the calculation should be done on both sides of the data point. This means that the first 2 and last 2 data points will have fewer values to average over.

The output moving_average will be a vector containing the calculated moving average for the selected column of the time series data.

gistlibby LogSnag