Conditional analysis in a raster layer based on values in another layer
If I have a bitmap stack:
require(raster)
r_test <- stack(
raster(ncols = 10, nrows = 10, vals = sample(c(-1, 0, 1), 100, TRUE)),
raster(ncols = 10, nrows = 10, vals = rnorm(100, 7, 0.4)
And I want to apply a function to layer.2 based on the value in the same cell in layer.1, how would I do that?
As a simple example, multiply the values at layer 2, where the equivalent cell in layer 1 is -1.
+3
source to share
1 answer
In general, the function overlay()
works reasonably well in many contexts. Conflicting my first stab at this answer, in my experience, ifelse()
can be significantly more or less effective, especially for larger rasters. For a 1000 row / column raster, simple raster algebra will be faster. If I remove this to 10,000 rows / columns then the call ifelse()
is better.
library(raster)
r_test <- stack(
raster(ncols = 1000, nrows = 1000, vals = sample(c(-1, 0, 1), 1000000, TRUE)),
raster(ncols = 1000, nrows = 1000, vals = rnorm(1000000, 7, 0.4))
)
## While overlay() works this is a more general solution and is
## more efficient for large raster data sets:
system.time(
r_out <- r_test[[1]] * r_test[[2]] * (r_test[[1]] == -1) + r_test[[2]] * (r_test[[1]] != -1)
)
# N=1000x1000 cells:
# user system elapsed
# 0.05 0.01 0.06
# N=10000x10000 cells:
# user system elapsed
# 48.36 19.60 77.56
system.time(
r_out <- overlay(x = r_test[[1]], y = r_test[[2]], fun = function(x, y) ifelse(x == -1, x * y, y))
)
# N=1000x1000 cells:
# user system elapsed
# 0.53 0.08 0.64
# N=10000x10000 cells:
# user system elapsed
# 19.77 5.82 26.53
+3
source to share