查找矩阵中最高值的行和列索引

alb*_*rto 3 r matrix

矩阵中最大值的位置(行和列)可以通过以下方式找到:

ma <- matrix(1:50, nrow = 5)
which(ma == max(ma), arr.ind = TRUE)
Run Code Online (Sandbox Code Playgroud)

如果我们不只想要最大值的坐标,而是想要 N 个最大值的坐标怎么办?

就像是:

order(ma, arr.ind = TRUE, decreasing = TRUE)[1:N] # this does not exist :(
Run Code Online (Sandbox Code Playgroud)

Ven*_*Yao 5

ma <- matrix(1:50, nrow=5)

# find the 5 largest values
x <- which(ma>=sort(ma, decreasing = T)[5], arr.ind = T)
# determine the order of the 5 largest values in decreasing order
x.order <- order(ma[x], decreasing = T)
x[x.order, ]
#      row col
# [1,]   5  10
# [2,]   4  10
# [3,]   3  10
# [4,]   2  10
# [5,]   1  10
Run Code Online (Sandbox Code Playgroud)