如何在R

时间:2015-11-28 19:12:14

标签: r stack raster

我有一个12层的rasterstack,我想提取第二个最高值及其相应的图层名称。 我发现代码按递减顺序将我的值排序为12个新图层:

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

现在,如果我只能这样做但返回相应图层的名称,它将全部回答。

谢谢, 皮尔

1 个答案:

答案 0 :(得分:0)

根据栅格的尺寸,您可以使用以下内容,我将在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]]

如果栅格的尺寸太大而无法使用上述方法,则可以依次识别每个图层的最高两个值,然后计算出哪个图层具有第二高的值:

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