Search code examples
rr-rasterrgdal

Summing RasterStacks when Rasterstacks are in a list of unknown length


I have a list of Rasterstacks each with 2 layers. I want to add all the Rasterstacks in a list together into a single Rasterstack with 2 layers. Assuming I have a list of 2 Rasterstacks, each with 2 layers, I would use the following command

raster_stack_sum = raster_list[[1]] + raster_list[[2]]

which would return a single Rasterstack with 2 layers. My question is how would I do this when the length of the list (ie the number of RasterStacks) is unknown. Is there an equivalent shorter way to run the below line of code when the length of the list (in this case 5) is unknown?

raster_stack_sum = raster_list[[1]] + raster_list[[2]] + 
raster_list[[3]]+ raster_list[[4]] + raster_list[[5]]

Solution

  • You can use stack to create a new RasterStack from a list of Raster* objects.

    Example data:

    library(raster)
    s <- stack(system.file("external/rlogo.grd", package="raster")) 
    x <- list(s, s, s)
    

    Solution:

    sum(stack(x))
    

    What makes you say that "storing a list of Rasterstacks is deprecated"?

    edit

    To sum a list of RasterStack objects layer by layer, I would use a loop

    y <- x[[1]]
    for (i in 2:length(x)) { y = y + x[[i]] }