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.


  # 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[[1]] – Pau Mar 18 '15 at 11:57

try this:

while (i<(nlayers(st1)-2)) {
 #moving averages
 img1= st1[[i]]
 img2= st1[[j]]
 mov_avg=(img1*img2*img3)/3 #or your function
 #write raster: the name of the output will be mov_avg_i.tif, where i= number of iteration (day?)
 writeRaster(mov_avg, paste("c:/mov_avg_",sep=i, ".tif",  format="GTiff", overwrite=TRUE)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.