在R中查找栅格堆栈中第二高值的图层名称

时间:2017-10-29 10:09:18

标签: r raster r-raster

关注这个问题(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)显示..

1 个答案:

答案 0 :(得分: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中存在联系,这两个函数可能会出现问题。