【问题标题】:Problem with the "stackApply" function in RR中的“stackApply”函数存在问题
【发布时间】:2020-11-08 19:30:47
【问题描述】:

我对 raster-package 中的“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'

【问题讨论】:

    标签: r-raster


    【解决方案1】:

    这是一个最小的、独立的、可重现的例子

    来自?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)
    

    如果所有值都是NAwhich.min 不会按预期返回NA。相反,它返回一个空向量。可以这样解决

    which.min(c(NA, NA, NA))[1]
    #[1] NA
    

    你可以做到

    w <- stackApply(s, indices=1, fun=function(x, ...) which.min(x)[1] )
    

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

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

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

    z <- which.min(s)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多