1

I have two single band rasters r1 and r2.

enter image description here

and

enter image description here

Put together in a GIS they look like this:

enter image description here

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!

I already tried:

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.

1
  • 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.
    – Spacedman
    Commented May 14, 2020 at 8:14

1 Answer 1

1

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)

Try adding them:

> 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:

enter image description here

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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