Thanks to @josliber's help (Rolling mean lag function), I was able to speed up a rolling mean function for different groups and rollmean lengths.
Now I'd like to add to this function the ability to loop through different variables and bind everything together.
Minimum reproducible example
library(zoo)
dat <- data.frame(fips = rep(c(1001, 1003), each = 100),
x = rnorm(200),
x2 = rnorm(200),
x3 = rnorm(200))
allFipsRM3 = function(dat, varName, len){
do.call(rbind, lapply(split(dat, dat$fips), function(x) {
all.rm <- as.data.frame(sapply(len, function(l) c(rollmean(x[,varName], l), rep(NA, l-1))))
colnames(all.rm) <- paste0(varName, "_rm", len)
cbind(data.frame(fips=x$fips[1]), all.rm, data.frame(year=seq_len(nrow(x))-1))
}))
}
outdat3 <- allFipsRM3(dat, "x", c(1, 2))
fips x_rm1 x_rm2 year
1001.1 1001 1.3482892 1.3043620 0
1001.2 1001 1.2604348 0.2990267 1
1001.3 1001 -0.6623813 -0.4243813 2
1001.4 1001 -0.1863812 0.2806624 3
1001.5 1001 0.7477061 -0.5111745 4
1001.6 1001 -1.7700551 -0.8463731 5