我们可以使用order和arrayInd函数。
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
arrayInd 中还有一个 .dimanmes 参数,您可以设置它。 arrayInd 是 which(, arr.ind = TRUE) 的主力。