1

I am trying to find the best way to apply a set of equations to a raster conditional on values in a separate raster. For example, suppose r1 has the values of interest and raster 2 (r2) is a raster with three values, 1, 2, and 3.

r1 <- raster(nrow=5, ncol=5)
r1[] <- runif(ncell(r1)) * 10
r2 = raster(nrow=5,ncol=5)
r2[] = round(runif(ncell(r2),1,3))
r3 = 0/r2 ## holder for values

I have modified code that applies a conditional function and applies it to a matrix, then assigns the values of the matrix to the raster.

Con=function(condition, trueValue, falseValue){
 return(condition * trueValue + (!condition)*falseValue)}

fun1 = function(x){x*1}
fun2 = function(x){x*2}
fun3 = function(x){x*3}
m = as.matrix(Con(r2 == 1,fun1(r1),Con(r2 == 2, fun2(r1), Con(r2 == 3,fun3(r1),0))))
values(r3) = m

This works, but (a) the conditional statement is highly unreadable, and (b) I am concerned that is will be prone to error with larger rasters.

Does anyone have a better way of doing this?

4

You could approach it this way:

f <- function(x,y) {
    z <- rep(NA, length(x))
    i <- which(y == 1)
    z[i] <- x[i] * 3
    i <- which(y == 2)
    z[i] <- x[i] * 33
    i <- which(y == 3)
    z[i] <- x[i] * 333
    z
}

library(raster)
r1 <- r2 <- raster(nrow=5, ncol=5)
r1[] <- runif(ncell(r1)) * 10
r2[] <- round(runif(ncell(r2),1,3))

x <- overlay(r1, r2, fun=f)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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