I'd do it with some ifelse replacement of the values in the raster:
Start with a blank raster:
> F = raster(a)
Then where a<0.2, take the value from c otherwise use NA:
> F[] = ifelse(a[]<0.2, c[], NA)
Then where a is over 0.5 set F to 1.85, otherwise use whatever was in F:
> F[] = ifelse(a[]>0.5, 1.85, F[])
And if a is between 0.2 and 0.5 take the value from b otherwise use whatever was in F:
> F[] = ifelse(a[]>=0.2 & a[]<=0.5, b[], F[])
This gives the same values as your E:
> all(F[]==E[])
[1] TRUE
Or you can do it by conditional replacement in the vector of raster values:
> F=raster(a)
> F[a[]<0.2] <- c[a[]<0.2]
> F[a[]>0.5] <- 1.85
> F[a[]>=0.2 & a[]<=0.5] <- b[a[]>=0.2 & a[]<=0.5]
> all(F[]==E[])
[1] TRUE
I'm not sure which is better in terms of speed or readability or flexibility. I'd wrap this all into a function anyway:
replacer = function(a, b, c,
low_thresh=0.2, high_thresh=0.5,
high_value=1.85){
...
}
and then benchmark it if speed is a concern. Otherwise use what you think looks best and is easiest for you to maintain.
Here's the three approaches (I've optimised the third one to avoid repeating tests):
replacer_1 = function(a, b, c,
low_thresh=0.2, high_thresh=0.5,
high_value=1.85){
E <- raster(a)
E[(a < low_thresh)] <- NA
E <- cover(E, c)
E[(a >= low_thresh) & (a <= high_thresh)] <- NA
E <- cover(E, b)
E[a > high_thresh] <- high_value
return(E)
}
replacer_2 = function(a, b, c,
low_thresh=0.2, high_thresh=0.5,
high_value=1.85){
F = raster(a)
F[] = ifelse(a[]<0.2, c[], NA)
F[] = ifelse(a[]>0.5, 1.85, F[])
F[] = ifelse(a[]>=0.2 & a[]<=0.5, b[], F[])
return(F)
}
replacer_3 = function(a, b, c,
low_thresh=0.2, high_thresh=0.5,
high_value=1.85){
low = a[]<low_thresh
F[low] <- c[low]
F[a[]>high_thresh] <- high_value
mid =a[]>=low_thresh & a[]<=high_thresh
F[mid] <- b[mid]
return(F)
}
Check they all return the same answer:
> E1 = replacer_1(a,b,c)
> E2 = replacer_2(a,b,c)
> E3 = replacer_3(a,b,c)
> all(E1[]==E2[])
[1] TRUE
> all(E1[]==E3[])
[1] TRUE
> all(E2[]==E3[])
[1] TRUE
Then use the microbenchmark package to compare:
> microbenchmark(replacer_1(a,b,c), replacer_2(a,b,c), replacer_3(a,b,c))
Unit: microseconds
expr min lq mean median uq
replacer_1(a, b, c) 50687.567 52486.878 54089.3265 53721.770 55221.1125
replacer_2(a, b, c) 2359.977 2507.661 2667.1080 2581.568 2642.9790
replacer_3(a, b, c) 485.086 504.377 543.6963 542.970 565.7025
which shows me that the third method is about 100 times as fast as the first one. Enjoy all the time I've saved you!
E[a > 0.5] <- 0.99- should that 0.99 be 1.85? - SpacedmanE <- cover(E, b)so did you mean "the values from raster b"? - Spacedman