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
.
Best Answer
As previously commented, you may accomplish all your task using R exclusively; in the following code, a raster is created and then filtered to values above the threshold, all other values will become NA, then the pixels are masked to the lines. Raster works now in recent versions with both
sf
andsp
objects, the code uses the latter kind.