Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To combine several SpatRasters using the sum function in the R package Terra, follow these steps:

  1. Load the Terra package and the SpatRasters you want to combine:
library(terra)

raster1 <- rast("raster1.tif")
raster2 <- rast("raster2.tif")
  1. Define the vector of SpatRasters to combine and use the terra::stack function to create a new SpatRaster stack:
raster_stack <- stack(raster1, raster2)
  1. Use the terra::apply function with the sum function to sum the values of each pixel across all the SpatRasters in the stack:
raster_sum <- apply(raster_stack, 1, sum)

This will create a new SpatRaster raster_sum with the same dimensions and resolution as the original rasters, but with the values of each pixel equal to the sum of the values of that pixel across all the SpatRasters in the stack.