how to sum a list of raster bricks

Viewed 14

I have a list of rasters and want to sum them up, however I am struggling to find a way to do it whilst preserving the layers. Below is an example showing two of the bricks in the list, but how to do it for all of them?

library(raster)

vals <- 1:5
many_bricks <- list()
for (v in vals){

b <- brick(system.file("external/rlogo.grd", package="raster"))*v

nam <- as.character(v)

many_bricks[[nam]] <- b

}

v1 <- many_bricks[[1]]+many_bricks[[2]]
1 Answers

We could Reduce

out <- Reduce(`+`, many_bricks)

-checking with manual addition

> out2 <- many_bricks[[1]]+many_bricks[[2]] + many_bricks[[3]]+many_bricks[[4]] + many_bricks[[5]]
> all.equal(out, out2)
[1] TRUE
Related