如果我有光栅堆栈:
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)
我想根据 layer.1 中相同单元格中的值将函数应用于 layer.2 ,我该怎么做?
举个简单的例子,将 layer.2 中的值乘以 layer.1 中的等效单元格等于-1。
答案 0 :(得分:3)
通常,overlay()
函数在很多情况下运行良好。根据我的经验,我对这个答案的第一次反击是矛盾的,ifelse()
可能会或多或少地显着提高效率,特别是对于较大的栅格。对于1000行/列的栅格,简单的栅格代数会更快。如果我将其增加到10000行/列,则ifelse()
调用会更好。
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