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?