I have two rasters (r1
and r2
) in R with the same spatial extent and I'd like to create a raster (r3
) that is conditional on values in r1
and r2
. I can set up a matrix and use raster::reclassify
, but I can only make this work using one of the rasters. I'm looking for an efficient way to do this on the two rasters. For example (see below) if r1 = 0
and r2 < 2
, r3 = 0.5
, but if r1 = 1
and r2 < 2
, r3 = .8
. Then if r1 = 0
and r2 > 2
, r3 = 0.7
, but if r1 = 1
and r2 > 2
, r3 = .9
(I have several more conditions that I'd like to use on the real data). Here is that example in code form.
library(raster)
# create two random rasters
r1 <- raster(matrix(rbinom(16, size=1, prob=.5), nrow=4))
r2 <- raster(matrix(rpois(16, 2), nrow=4))
# check that spatial extent is the same
extent(r1) == extent(r2)
# here is a reclassify matrix if r1==1
reclass_m1 <- matrix(
c(0,2,.8,
3,5,.9
), ncol=3, byrow=TRUE
)
# reclassify matrix if r1==0
reclass_m0 <- matrix(
c(0,2,.5,
3,5,.7
), ncol=3, byrow=TRUE
)
# so if r1==1, I would want
r3 <- reclassify(r2, reclass_m1)
# if r1==0, I would want
r3 <- reclassify(r2, reclass_m0)
# but I want a single r3 that does this process consistently.
I looked at other similar questions and I didn't find exactly the solution I was looking for. I appreciate your help in advance.
If
r1
andr2
are comparable, you can just use logical indexing. This might get a bit tedious if you have a ton (or a varying amount) of conditions, but for this example it certainly works: