How to find second highest value and corresponding layer name in a raster stack in R

霸气de小男生 提交于 2019-12-13 05:46:15

问题


I have a rasterstack with 12 layers and I would like to extract the 2nd highest value along with its corresponding layer name. I found codes to order my values into 12 new layers in decreasing order:

rs_ord <- calc(inraster, fun=function(X,na.rm) X[order(X,decreasing=T)])

Now, if I could only do the same but return the corresponding layer's name, it would answer it all.

Thanks, Pierre


回答1:


Depending on the dimensions of your rasters, you may be able to use the following, which I'll demonstrate with dummy data in RasterStack s:

library(raster)
s <- stack(replicate(12, raster(matrix(runif(100000), 1000))))

# coerce s to a data.frame
d <- s[]
# return the second-highest value
sort(d, decreasing=TRUE)[2]
# identify the column containing the second-highest value
col(d)[order(d, decreasing=TRUE)[2]]

If the raster's dimensions are too large to use the above approach, you can instead identify the highest two values of each layer in turn, and then work out which layer has the second-highest value:

# return a matrix whose columns contain the top two values per layer
top_two <- sapply(seq_len(nlayers(s)), function(i) {
  sort(s[[i]][], decreasing=TRUE)[1:2]
})
# return the second-highest value
sort(top_two, decreasing=TRUE)[2]
# identify the column containing the second-highest value
col(top_two)[order(top_two, decreasing=TRUE)[2]]


来源:https://stackoverflow.com/questions/33975346/how-to-find-second-highest-value-and-corresponding-layer-name-in-a-raster-stack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!