This line given below will simply calculate the moving average for certain values with a window of 3. As the total number of values is 12 and the moving-average widow is 3, the number of resulted values is 10 (as shown below).
library(zoo)
x <- c(1,2,3,NA,NA,4,6,5,6,4,2,5)
movingmean <- rollapply(x, 3, FUN = mean, na.rm = T)
movingmean
# [1] 2.000000 2.500000 3.000000 4.000000 5.000000 5.000000
# [7] 5.666667 5.000000 4.000000 3.666667
I want to subtract these averages (movingmean) from the corresponding original value.
Example: 2-2.000000, 3-2.500000, NA-3.000000, NA-4.000000, ..., 2-3.666667.
By default,
rollapplydoes not pad the result withNA. Setfill=NAto do so.Also note that
rollapplyuses a centered window by default. You can change it via thealignargument or userollapplyrif you want a right-aligned calculation (as with most time series).