2017-10-29 8 views
0

この質問(Find second highest value on a raster stack in R)に続いて、2番目に高い値を持つレイヤの名前を各ラスタスタックxy座標でどのように見つけることができますか?ラスタスタックの2番目に高い値のレイヤ名を見つけるR

私は「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) 

を2番目に高い値を含む名前(層番号)?

私は(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

は二番目に高い指標を報告するwhich.max.na機能を変更するアプローチです。 NA以外の値が1つしかない場合は、0という報告をするためにsum(!is.na(x)) == 1を追加したことに注目してください。

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の最初の6つの値のように、両方の関数が期待通りに機能します。

最後に、RasterStackに結び付きがあると、これらの2つの機能に問題が生じる可能性があることに注意してください。

+0

これは完璧に動作します、ありがとう! – Marc

関連する問題