我对光栅包中的“stackApply”函数有疑问。首先,我想堆叠三个栅格层(每个层有一个波段) - 这是可行的。然后我想创建一个栅格对象,显示最小值出现在三个波段/图层中的哪一个(栅格图层中的每个像素都有不同的值)。但我收到各种错误消息。有谁知道我该如何解决这个问题? 谢谢你
stacktest<-stack(test,test1,test2)
min_which <- stackApply(stacktest, indices=1, fun=function(x, na.rm=NULL)which.min(x))
Error in setValues(out, v) : values must be a vector
Error in is.infinite(v) : not implemented standard method for type 'list'
这是一个最小的、独立的、可重现的示例:
示例数据来自
?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)