3

I need to sum several rasters (.tiff) with different extent but the same resolution in R.

How can I do it?

  • Do you need the minimum or maximum extent as output? – aldo_tapia Aug 22 '17 at 13:05
  • the maximum @aldo_tapia – Joan Gimenez Aug 22 '17 at 13:32
  • 1
    You can use extend() with the maximum extent. I'll post an elaborate answer in a few hours – aldo_tapia Aug 22 '17 at 13:41
6

Sample data:

r1 = raster(xmn=0,xmx=11,ymn=0,ymx=11,res=1)
r1[]=1:ncell(r1)
r2 = raster(xmn=5,xmx=8,ymn=6,ymx=9,res=1)
r2[]=1:ncell(r2)+5

Now two functions, first to get the max extent of a list of rasters:

extend_all =
function(rasters){
 extent(Reduce(extend,rasters))
}

Then one to sum all rasters padded to a specified extent:

sum_all =
function(rasters, extent){
 re = lapply(rasters, function(r){extend(r,extent)})
 Reduce("+", re)
}

Then:

r_sum = sum_all(list(r1,r2), extend_all(list(r1,r2)))
plot(r_sum)

enter image description here

Note this pads small rasters out with NA values. If you want zeroes instead use

sum_all = 
function(rasters, extent){
 re = lapply(rasters, function(r){extend(r, extent, value=0)})
 Reduce("+",re)
} 

This might be useful if your data is 0/1 counts and you are summing ones in each cell from rasters with varying extents.

2

Sorry unable to comment as I don't have a 50 rep yet, but Spacedman's solution for getting the max extent is very slow on large datasets, this is much faster:

rasters <- list(ras_01, ras_02, ras_03, ras_04, ras_10, ras_13, ras_19, ras_22)
getMaxExtent <- function(rasters) {
  extents <- sapply(rasters, FUN = function(x) {
    raster::extent(x)
  })
  r <- raster(ext = extents[[1]], nrows = rasters[[1]]@nrows, ncols = rasters[[1]]@ncols)
  max_extent <- sapply(extents, FUN = function(x) {
    r <<- raster::extend(r, x)
  })
  raster::extent(r)
}

getMaxExtent(rasters)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.