簡體   English   中英

在R中的柵格堆棧中查找次高值的圖層名稱

[英]Find layer names for the second highest values in a raster stack in R

緊接着這個問題( 在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)

但是,如何獲得名稱(層號)包含第二高值的柵格?

我嘗試了( 如何在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)所示。

這是一種修改which.max.na函數以報告第二高索引的方法。 請注意,我添加了sum(!is.na(x)) == 1以使該函數在只有一個非NA值時報告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中存在聯系,則這兩個功能可能會出現問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM