I need to calculate the running average by year for each column. My data example:
dat <- data.frame(yr = c(1980, 1980, 1980, 1980, 1980, 1981, 1981, 1981, 1981, 1981, 1982, 1982, 1982, 1982, 1982), data1 = c(-10.16, -7.48, -3.31, -6.04, -11.68, -13.40, -10.41, -10.65, -6.70, -17.05, -25.62, -29.14, -16.65, -6.42, 0.28), data2 = c(2.30, -7.52, -13.26, -13.24, -14.74, -9.38, -8.93, -11.78, -14.07, -11.66, -8.82, -10.30, -7.99, -10.02, -15.36), data3 = c(-14.83, -15.08, -16.44, -18.95, -13.40, -7.16, -4.35, -1.61, -0.01, -0.35, -2.09, -3.12, 0.87, -0.06, 2.29))
The running average is calculated as follows:
library(TTR)
library(dplyr)
runavg <- with(dat, ave(data1, yr, FUN=function(x)
TTR::runMean(x, n=3)) )
The question is simple, but I would like to ask you to explain in more detail how to apply this code to every column? I tried various solutions using lapply, function, mutate... I just realized that I do not have enough knowledge in this area :(. I will be very grateful for the help.