首页 > 解决方案 > 定位输出矩阵的哪些元素

问题描述

如果我有一个 100 x 100 矩阵并且我想找到最高的 20 个值并且我成功地使用:

mat <- matrix(data = rexp(200, rate = 10), nrow = 100, ncol = 100)
tail(sort(mat), 20)

#[1] 0.6599044 0.6599044 0.6599044 0.6599044 0.6599044 0.6601134 0.6601134 0.6601134 0.6601134 0.6601134
#[11] 0.6669251 0.6669251 0.6669251 0.6669251 0.6669251 1.0284198 1.0284198 1.0284198 1.0284198 1.0284198

但是现在我如何在矩阵中输出它们的位置?

标签: rmatrixoutputtail

解决方案


我们可以使用orderarrayInd运行。

mat <- matrix(data = rexp(200, rate = 10), nrow = 100, ncol = 100)
arrayInd(order(mat, decreasing = TRUE)[1:20], .dim = dim(mat))

一个小例子

set.seed(0)
mat <- round(matrix(data = rexp(25, rate = 10), nrow = 5, ncol = 5), 4)
#       [,1]   [,2]   [,3]   [,4]   [,5]
#[1,] 0.0184 0.1230 0.0762 0.1876 0.0642
#[2,] 0.0146 0.0540 0.1238 0.0655 0.0294
#[3,] 0.0140 0.0957 0.4424 0.0337 0.0566
#[4,] 0.0436 0.0147 0.1055 0.0588 0.0106
#[5,] 0.2895 0.1391 0.1035 0.2365 0.0059

## 1D index of the first 4 largest values
ind1D <- order(mat, decreasing = TRUE)[1:4]
# [1] 13  5 20 16

## 2D index
ind2D <- arrayInd(ind1D, .dim = dim(mat))
#     [,1] [,2]
#[1,]    3    3
#[2,]    5    1
#[3,]    5    4
#[4,]    1    4

## inspect corresponding matrix elements, using either 1D or 2D index
mat[ind1D]
#[1] 0.4424 0.2895 0.2365 0.1876

mat[ind2D]
#[1] 0.4424 0.2895 0.2365 0.1876

还有一个.dimanmes参数arrayInd可以设置。arrayInd是 的主力军which(, arr.ind = TRUE)


推荐阅读