0

I want ro calculate the differences between rasters within a raster stack with a certain step, and I am unsure how to do so.

What I want is to subtract every element from its 5th next one, something like layer1-layer5, layer5-layer9, layer9 -layer13 and so on.

I tried to use the following to avoid loops but it does not work.

    r = raster(matrix(1:30,5,6))
    mstack<-stack(r,r,r,r,r,r,r,r,r,r,r,r,r,r,r,r,r,r,r,r,r,r,r,r)
    msub<-subset(mstack, 1:nlayers(mstack)) - subset(mstack, 1:(nlayers(mstack)+5)) 
  • 1
    I think you want this: msub < -subset(mstack, 1:(nlayers(mstack)-4)) - subset(mstack, 5:nlayers(mstack)) In your second subset you are adding five to the total number of layers which is what is causing the invalid subset error. – Jacob F Apr 2 at 13:42
  • 1
    Do you also want layer2-layer6? All layer[n]-layer[n+4] for all n such that [n+4]<= total number of layers – Spacedman Apr 2 at 14:32
  • @Spacedman yes, apologies for my english, this is what I try to do but I messed up the subsets. – foo Apr 2 at 14:34
  • 1
    Do you need to use subset? Can you directly access layers thus: nl=nlayers(mstack); mstack[[1:(nl-4)]] - mstack[[5:nl]]? You can see the pairs of layers being subtracted with cbind(1:(nl-4), 5:nl) – Spacedman Apr 2 at 14:39
  • Thank you @Spacedman, it took me some hours but it worked! Can you please post this as answer to accept it? – foo Apr 3 at 10:20

Your Answer

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

Browse other questions tagged or ask your own question.