本文介绍了如何在R的栅格堆栈中找到第二高的值和相应的图层名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 12 层的栅格堆栈,我想提取第二个最高值及其相应的图层名称.我找到了将我的值按降序排列到 12 个新层的代码:

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.

谢谢,皮埃尔

推荐答案

根据栅格的尺寸,您可以使用以下内容,我将在 RasterStack ss 中使用虚拟数据进行演示代码>:

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]]

这篇关于如何在R的栅格堆栈中找到第二高的值和相应的图层名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:31