Reclassifying raster stack based on condition and other layers using R?

I want to reclassify raster r1 in the following form:

• all the values that are larger than r2 to be 1
• all the values that are less than r3 to be 0
• all the rest of the values to be equal to r4

I use overlay to set the values for the first two conditions, but I can't do that for the third one. I am also interested to know how to put all these in one function.

library(raster)
r1 <- raster(nrow=5, ncol=5)
r1 <- setValues(r1, runif(ncell(r1)))
r2 <- setValues(r1, runif(25 ,0.6,0.9))
r3 <- setValues(r1, runif(25 ,0.2,0.4))
r4 <- setValues(r1, runif(25 ,1,2))

x <- overlay(r1, r2, fun=function(x,y){ x[x>y] <- 1; x})
x2 <- overlay(x, r3, fun=function(x,y){ x[x<y] <- 0; x})

To put this into a vectorized function you can use ifelse. If you stack your rasters then you do not need to piecemeal the reclassification and can apply a function to the stack.

Prepare data

library(raster)
r1 <- raster(nrow=5, ncol=5)
r <- stack(setValues(r1, runif(ncell(r1))),
setValues(r1, runif(25 ,0.6,0.9)),
setValues(r1, runif(25 ,0.2,0.4)),
setValues(r1, runif(25 ,1,2)))

Write reclassification function

rc <- function(x1,x2,x3,x4) {
ifelse( x1 > x2, 1, ifelse( x1 < x3, 0, x4) )
}

Apply function to raster stack

r.class <- overlay(r, fun=rc)

The bracket extract operators work on rasters in R. So you dont need to use setValues or overlay. I would do this:

r1[r1 > r2] <- 1
r1[r1 < r3] <- 0
r1[!(r1 > r2 | r1 < r3)] <- r4[!(r1 > r2 | r1 < r3)]

This should work if all of your rasters are the same extent and resolution.

• Thanks this works well, but I need to put them all in function cause I'm working with multiple layers. – Geo-sp Oct 22 '15 at 23:16