Merge rasters with different origins in R

There was an issue with projectRaster's alignOnly that was fixed in raster 3.4-8 on github on Dec 22nd, 2020. To align and merge two rasters (r1 & r2) this code should work.

template<- projectRaster(from = r2, to= r1, alignOnly=TRUE)
#template is an empty raster that has the projected extent of r2 but is aligned with r1 (i.e. same resolution, origin, and crs of r1)
r2_aligned<- projectRaster(from = r2, to= template)
r_merged<- merge(r1,r2) 
r_merged2<- mosaic(r1,r2, fun=mean, na.rm=TRUE)

In merge function if objects overlap, the values get priority in the same order as the arguments (but NA values are ignored), but in mosaic a function is applied to compute cell values in areas where layers overlap.

For combining more than 2 rasters you must first align them all using projectRaster, and then you can put them in a list and use do.call

#For merge
x <- list(r1, r2, r3)
m <- do.call(merge, x)

#For mosaic
x <- list(r1, r2, r3)
names(x)[1:2] <- c('x', 'y')
x$fun <- mean
x$na.rm <- TRUE

m <- do.call(mosaic, x)

Tags:

Merge

R

Raster