I want to calculate a rolling mean (backward and forward) over 15 days each. Here is a testframe:
date_list = seq(ymd('2000-01-15'),ymd('2010-09-18'),by='day')
testframe = data.frame(Date = date_list)
testframe$Day = substr(testframe$Date, start = 6, stop = 10)
testframe$V1 = runif(3900, 2.0, 35.0)
testframe$V2 = runif(3900, 5.0, 40.0)
testframe$V3 = runif(3900, -10.0, 10.0)
testframe$V4 = seq(from = 5, to = 45, length.out = 3900)
I know how to calculate it for each individual column:
library(zoo)
rollmean(testframe$V4, 31)
rollapply(testframe$V4, 31, mean)
But how can I do this for each column at once? I think I have to exclude the Day and Date column for that, but how can I do that within the command? And how can I get the results in my old testframe with NAs for the first and last 15 days?
I tried this:
testframe[paste0("new_col",1:4)] <- lapply(testframe[,3:6], rollapply, FUN = mean, width = 31)
But it doesnt work!