# Subsetting rasterstack for subtraction between elements using R?

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))
``````
• 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 '19 at 13:42
• 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 '19 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 '19 at 14:34
• 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 '19 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 '19 at 10:20