与多个栅格相关的嵌套条件语句

Nested conditional-statements relating multiple rasters

假设我有四个栅格文件:x、y、w 和 z,我想使用多个嵌套条件基于所有文件的关系(即网格单元的层次顺序)创建一个新的栅格文件根据以下功能:

x <- raster(nrows=100, ncols=100)
  x[] <- runif(ncell(x), min = 0, max = 100)
y <- raster(nrows=100, ncols=100)
  y[] <- runif(ncell(y), min = 0, max = 100)
w <- raster(nrows=100, ncols=100)
  w[] <- runif(ncell(w), min = 0, max = 100)
z <- raster(nrows=100, ncols=100)
  z[] <- runif(ncell(z), min = 0, max = 100)

My.fun <- function(x,y,z,w){
ifelse(x > y && x > w && x > z,
1,
ifelse(y > x && y > w && y > z,
2,
ifelse(w > x && w > y && w > z,
3,
ifelse(z > x && z > y && z > w,
4,NA),NA),NA),NA)
}

res <- overlay(x, y, z, w, fun = Vectorize(My.fun))

这是我到目前为止想出的。然而,它似乎不起作用。想知道是否有人可以帮助我并阐明我如何解决这个问题?

错误信息:

Error in (function (x, fun, filename = "", recycle = TRUE, forcefun = FALSE, : cannot use this formula, probably because it is not vectorized"

非常感谢。

这里有几个问题。首先,您的 ifelse 语句参数太多(前 3 个在末尾有不必要的 NA。其次,您需要比较每个栅格中的数据,例如使用 x[] < y[] 而不是 x < y。第三,你应该有一个 & 而不是 &&

这样,你的函数就已经矢量化了:

My.fun <- function(x,y,z,w){
  ifelse(x[] > y[] & x[] > w[] & x[] > z[], 1,
         ifelse(y[] > x[] & y[] > w[] & y[] > z[], 2,
                ifelse(w[] > x[] & w[] > y[] & w[] > z[], 3,
                       ifelse(z[] > x[] & z[] > y[] & z[] > w[], 4, NA))))
}

所以你可以这样做:

My.fun(x, y, w, z)
#>    [1] 3 1 3 2 3 4 2 3 1 3 4 4 3 4 1 2 2 1 2 3 4 3 4 4 1 1 3 2 3 1 2 4 2 4 2 4
#>   [37] 1 4 4 2 2 4 1 2 3 2 2 3 1 1 1 2 3 4 4 4 3 4 4 2 3 2 2 4 2 2 3 1 1 4 1 4
#>   [73] 2 2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 9000 entries ]

wxyz <- raster(nrows=100, ncols=100)
wxyz[] <- My.fun(x,y,z,w)
wxyz
#> class      : RasterLayer 
#> dimensions : 100, 100, 10000  (nrow, ncol, ncell)
#> resolution : 3.6, 1.8  (x, y)
#> extent     : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#> crs        : +proj=longlat +datum=WGS84 
#> source     : memory
#> names      : layer 
#> values     : 1, 4  (min, max)