I'm looking for an equivalent of the conditional expression "Con" from arcpy in an open source spatial analysis package. I'd prefer to use QGIS or R.
To provide some additional detail, I need to evaluate some moderately complicated conditional statements in map algebra, e.g., if the value for one raster is above a certain threshold, use one value, but if the value is below that threshold, use a value based on whether another raster value is above or below another threshold, e.g.:
newraster = Con(raster1 < 4, 0, Con(raster2 > 3, 0.5, 1))
Caveat: I have not been able to confirm that the above code will execute, since the machine I'm currently using does not have any ESRI products installed.
Answer
Its a one-liner - the trick is to add the true value times the condition being true to the false value times the condition being not true. Only one of those parts will be true, so you end up getting the value you want.
Con=function(condition, trueValue, falseValue){
return(condition * trueValue + (!condition)*falseValue)
}
Sample:
r=raster(matrix(1:12,3,4))
q=Con(r<6,0,1)
Your case:
raster1=r
raster2=raster(matrix(12:1,3,4))
as.matrix(raster1)
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
as.matrix(raster2)
[,1] [,2] [,3] [,4]
[1,] 12 9 6 3
[2,] 11 8 5 2
[3,] 10 7 4 1
q = as.matrix(Con(raster1<4,0,Con(raster2>3,.5,.1)))
as.matrix(q)
[,1] [,2] [,3] [,4]
[1,] 0 0.5 0.5 0.1
[2,] 0 0.5 0.5 0.1
[3,] 0 0.5 0.5 0.1
Conditional that takes a value from a raster:
as.matrix(Con(raster1>6,0,raster2))
[,1] [,2] [,3] [,4]
[1,] 12 9 0 0
[2,] 11 8 0 0
[3,] 10 7 0 0
Not tested with NA's though...
This is just the raster version of ifelse
.
No comments:
Post a Comment