I have the RasterStack called stack_raw. The dimensions are 517, 626, 323642, 46 (nrow, ncol, ncell, nlayers) . I want to add an empty layer to a n position. I´m trying this way, but it sounds a bit stupid:

#Creating the empty raster with the same dimensions:
a<-raster(nrow=517, ncol=626, ext=extent(stack_raw), crs=crs(stack_raw))

#Separating the RasterStack in parts, in order to add the layer on that position:
stack_raw12<-subset(stack_raw, 1:2)
stack_raw346<-subset(stack_raw, 3:46)

#Adding the layer in the position of the middle:0
stack_raw12a<-addLayer(stack_raw12, a)

#Joining everybody:
stack_rawfull<-addLayer(stack_raw12a, stack_raw346)

Does anyone know a more intelligent way to do that?

  • I'd try just subsetting out the ones after stacking all together, i.e. subset(stack(stack_raw, a), c(1:2, 47, 3:46))
    – mdsumner
    Commented Mar 31, 2017 at 15:12

1 Answer 1


I think it should work to stack them all together and index that with subset:

subset(stack(stack_raw, a), 
    c(1:2, 47, 3:46))

You could be more nuanced with the index, i.e.

nl <- nlayers(stack_raw)
subset(stack(stack_raw, a), 
     c(1:2, nl + 1, 3:nl))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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