这是一个最小的、独立的、可重现的例子:
来自?stackApply的示例数据
library(raster)
r <- raster(ncol=10, nrow=10)
values(r) <- 1:ncell(r)
s <- stack(r,r,r,r,r,r)
s <- s * 1:6
现在将这些数据与您的函数一起使用(我删除了 na.rm=NULL,因为它没有被使用)
w <- stackApply(s, indices=1, fun=function(x, ...) which.min(x) )
w
#class : RasterLayer
#dimensions : 10, 10, 100 (nrow, ncol, ncell)
#resolution : 36, 18 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#crs : +proj=longlat +datum=WGS84 +no_defs
#source : memory
#names : index_1
#values : 1, 1 (min, max)
which.max 也一样
w <- stackApply(s, indices=1, fun=function(x, na.rm=NULL) which.max(x) )
w
# (...)
#values : 6, 6 (min, max)
这表明它工作正常。在大多数情况下,这意味着您的单元格可能是NA
s[1:10] <- NA
w <- stackApply(s, indices=1, fun=function(x, ...) which.min(x) )
# Error in setValues(out, v) : values must be numeric, logical or factor
很容易看出为什么会出现这个错误
which.min(3:1)
#[1] 3
which.min(c(3:1, NA))
#[1] 3
which.min(c(NA, NA, NA))
#integer(0)
如果所有值都是NA,which.min 不会按预期返回NA。相反,它返回一个空向量。可以这样解决
which.min(c(NA, NA, NA))[1]
#[1] NA
你可以做到
w <- stackApply(s, indices=1, fun=function(x, ...) which.min(x)[1] )
但是,将stackApply 与indices=1 一起使用并不是一个好方法。您通常应该使用calc 来计算所有层的单元格值。
y <- calc(s, function(x) which.min(x)[1])
但在这种情况下,您可以使用更直接的方式
z <- which.min(s)