I want to compute any type of "moving statistic" on a time series in R, beyond a moving average. For example, how would I compute a moving standard deviation over a time window of length 3?
I've tried the following:
#example data
x <- c(3,9,2,8,4,6,5,8)
#moving standard deviation over a time window of length 3
msd3 <- (cumsum(x^2)-cumsum(Lag(x^2,3)))/((1:length(x))-(Lag(1:length(x),3)))-((cumsum(x)-cumsum(Lag(x,3)))/((1:length(x))-(Lag(1:length(x),3))))^2
But not only does it not work (because the cumsum of the lagged vector gives a vector of all NAs), but I stopped trying to solve that last issue because it seems unnecessarily complicated. Any elegant solution to that problem?