# R 'overlay' two rasters to create one single band raster and preserve cell values

I have two single band rasters `r1` and `r2`.

and

Put together in a GIS they look like this:

Raster extend and cell size of `r1` and `r2` match perfectly. The white areas are nodata cells. There is no overlapping of cells that have a cell value.

I would like to 'overlay' the two rasters to create one single band raster!

``````r_overlay <- overlay(r1, r2, fun=sum)
``````

and

``````r_mean <- mean(r1, r2)
``````

and

``````r_brick <- brick(r1, r2)
``````

but none of the approaches seems to work. The goal is to create a single band raster containing the values of both rasters `r1` and `r2` and nodata values where there are nodata values now.

• tip: when asking questions please try and supply code for creating test data and also explain why things don't "seem to work". We can't tell what went wrong when you tried those things you tried. Commented May 14, 2020 at 8:14

`sum` (or `overlay` with `sum`) works if you add `na.rm=TRUE`.

Test data - an upper and lower triangle with 5 or 7 and NA:

``````> r1 = 5*raster(upper.tri(matrix(1:64,8,8)))
> r1[r1==0]=NA
> r2 = 7*raster(!upper.tri(matrix(1:64,8,8)))
> r2[r2==0]=NA
``````

Plot them - these should show triangles with a single value and empty cells:

``````> plot(r1)
> plot(r2)
``````

``````> plot(r1+r2)
> plot(sum(r1,r2))
``````

And everything is `NA` because there's an `NA` in one of the two rasters everywhere. So exclude:

``````> rsum = sum(r1,r2,na.rm=TRUE)
> plot(rsum)
``````

gives:

a complete square of 5s and 7s. If you had any parts with `NA` in both rasters, that would be `NA` in the output. If you had cells that were a 5 in one raster and a 7 in the other, you'd get a 12 in the output.

• This works, thanks a lot! Commented May 14, 2020 at 10:23