Ask Your Question
0

What is the procedure for combining several SpatRasters using the sum function in the R package Terra?

asked 2023-05-15 07:12:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-15 07:27:01 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-15 07:12:00 +0000

Seen: 9 times

Last updated: May 15 '23