R中的“ stackApply”函数出现问题

问题描述

我对栅格数据包中的“ 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)
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,na.rm=NULL) which.max(x) )
w
# (...)
#values     : 6,6  (min,max)

这表明它工作正常。在大多数情况下,这意味着您可能拥有NA

的单元格
s[1:10] <- NA
w <- stackApply(s,...) 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))[1]
#[1] NA

你可以做

w <- stackApply(s,...) which.min(x)[1] )

但是,将stackApplyindices=1一起使用不是一个好方法。通常,您应该使用calc计算所有图层上的像元值。

y <- calc(s,function(x) which.min(x)[1])

但是在这种情况下,您可以使用更直接的

z <- which.min(s)