# Looping a raster stack with a step, R

I have a large raster stack of about 500 rasterlayers. What I want to do is to extract specific layers and store them in a different strack. The layers for which I am interested in, have a step of 8 (e.g. I want layers 1,9,17,25,...). I have tried to do this with the following loop but I get Error in compareRaster(x, value) : different extent.

What is wrong with my code?

``````new<-stack()
for (i in seq(1,500,8)){
new[[i]]<-old[[i]]
}
``````

I managed to solve this by setting new as `list()` instead of `stack()`.

Can someone explain to me the error?

You can extract multiple layers by subsetting. Test:

Make a stack of six rasters:

``````> r = raster(matrix(1:12,3,4))
> s = stack(r,r,r,r,r,r)
> s
class       : RasterStack
dimensions  : 3, 4, 12, 6  (nrow, ncol, ncell, nlayers)
resolution  : 0.25, 0.3333333  (x, y)
extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. : NA
names       : layer.1, layer.2, layer.3, layer.4, layer.5, layer.6
min values  :       1,       1,       1,       1,       1,       1
max values  :      12,      12,      12,      12,      12,      12
``````

Get the odd-numbered ones:

``````> s[[c(1,3,5)]]
class       : RasterStack
dimensions  : 3, 4, 12, 3  (nrow, ncol, ncell, nlayers)
resolution  : 0.25, 0.3333333  (x, y)
extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. : NA
names       : layer.1, layer.3, layer.5
min values  :       1,       1,       1
max values  :      12,      12,      12
``````

returning a stack with three layers.

In your case you have to create the vector from 1 to 500 in steps of 8, for which you can use `seq(1,500,by=8)` and its done.

Your error occurs because your empty initial stack has no structure and R doesn't like it:

``````> new=stack()
> new[[1]]=r
Error in compareRaster(x, value) : different number or columns
>
``````

If you initialise the stack with a raster of the right size you can then add more rasters to it, but you can't start with an empty stack:

``````> new=stack(r)
> new[[2]]=r
> new[[3]]=r
> new[[4]]=r
> new
class       : RasterStack
dimensions  : 3, 4, 12, 4  (nrow, ncol, ncell, nlayers)
``````
• Thanks @Spacedman. It's useful to know that. I would expect such an error in case when I would have stored a raster of different dimensions in my new stack before the loop...Thank you. – foo Jan 23 at 8:56