【问题标题】:Find layer names for the second highest values in a raster stack in R在R中的栅格堆栈中查找第二高值的图层名称
【发布时间】:2017-10-29 10:09:18
【问题描述】:

根据这个问题 (Find second highest value on a raster stack in R),如何才能找到对于每个栅格堆栈 xy 坐标的具有第二高值的图层的名称?

我可以使用“which.max()”函数找到包含最大值的层的名称(层号):

set.seed(123)
require(raster)
r1 <- raster(nrows = 10, ncols = 10)
r2 <- r3 <- r4 <- r1
r1[] <- runif(ncell(r1))
r2[] <- runif(ncell(r1)) + 0.2
r3[] <- runif(ncell(r1)) - 0.2
r4[] <- runif(ncell(r1))
rs <- stack(r1, r2, r3, r4)

which.max.na <- function(x, ...) ifelse(length(x) == sum(is.na(x)), 0, which.max(x))

m1 <- calc(rs, which.max.na)

plot(m1)

但是,如何获得名称(图层编号)包含第二高值的栅格?

我在 (How to find second highest value and corresponding layer name in a raster stack in R) 中尝试了解决方案:

m2 <- calc(rs, fun=function(x, na.rm) x[order(x, decreasing=T)[2]]) & calc(rs, fun=function(x, na.rm) order(x, decreasing=T)[2])

plot(m2)

但没有成功,如plot(m2) 所示..

【问题讨论】:

    标签: r raster r-raster


    【解决方案1】:

    这是一种修改which.max.na 函数以报告第二高索引的方法。请注意,当只有一个非 NA 值时,我添加了 sum(!is.na(x)) == 1 以让函数报告 0

    which.second.max.na <- function(x, ...) 
      ifelse(length(x) == sum(is.na(x)) | sum(!is.na(x)) == 1, 0, 
             which.max(`[<-`(x, which.max(x), NA)))
    
    m2 <- calc(rs, which.second.max.na)
    

    我们可以打印前几个值来查看which.max.nawhich.second.max.na 是否有效。

    head(values(m1))
    [1] 2 1 4 2 1 2
    
    head(values(m2))
    [1] 4 3 2 1 2 3
    
    head(values(rs))
           layer.1   layer.2    layer.3     layer.4
    [1,] 0.2875775 0.7999890 0.03872603 0.784575267
    [2,] 0.7883051 0.5328235 0.76235894 0.009429905
    [3,] 0.4089769 0.6886130 0.40136573 0.779065883
    [4,] 0.8830174 1.1544738 0.31502973 0.729390652
    [5,] 0.9404673 0.6829024 0.20257334 0.630131853
    [6,] 0.0455565 1.0903502 0.68024654 0.480910830
    

    似乎对于来自 RasterStack 的前六个值,两个函数都按预期工作。

    最后,请注意,如果 RasterStack 中存在关联,这两个函数可能会出现问题。

    【讨论】:

      猜你喜欢
      • 2014-11-01
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 2013-05-07
      • 2017-01-26
      • 2016-04-19
      相关资源
      最近更新 更多