# How to compute climatology of 3 days moving averages for rasters pixel by pixel?

I have one year of datasets that I want to compute the climatology of 3-day moving averages and then I subtract this climatology from the original values for each pixel.

example:

``````  # Set up the rasters
r1 <- r2 <- r3 <- r4 <- r5 <- r6 <- raster(nrows=10, ncols=10);
# Populate them with some values
r1 <- setValues(r1,runif(100,min=1,max=100));
r2 <- setValues(r2,runif(100,min=1,max=100));
r3 <- setValues(r3,runif(100,min=1,max=100));
r4 <- setValues(r4,runif(100,min=1,max=100));
r5 <- setValues(r5,runif(100,min=1,max=100));
r6 <- setValues(r6,runif(100,min=1,max=100));
# Stack them
st1 <- stack(r1,r2,r3,r4,r5,r6)
``````

Any idea on how to do this.

``````x <- calc(st1, function(x) movingFun(x, 3, mean))
y <- st1 - x
``````

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

• Thanks then how to rewrite `(r1 ,r2 ,r3 ,r4 , r5 ,r6)` from `y` – usersam Mar 18 '15 at 8:13
• @usersam r1<-y[] – Pau Mar 18 '15 at 11:57

try this:

``````i=1
while (i<(nlayers(st1)-2)) {
j=i+1
k=i+2
#moving averages
img1= st1[[i]]
img2= st1[[j]]
img3=st1[[k]]