Search code examples
rstackraster

Stack raster in a loop


I need to stack some rasters in a loop like:

for(month in 1:12){
.
.
.
"some algorithm spiting out a raster called 'sm_esa'"
sm_esa_stack<-stack(sm_esa)
}

In the end I'd like to create a stack with 12 layers (one month each). But my last line obviously overwrites with every new raster rather than stacks on. Any hint?


Solution

  • Instantiate an empty stack outside the loop and after each iteration of your loop, add the new rasterLayer to the stack by stacking both the current stack and the new Rasterlayer.

    x <- stack()
    for(month in 1:12){
    .
    .
    .
    "some algorithm spiting out a raster called 'sm_esa'"
    x <- stack( x , sm_esa )
    }