在矩阵中查找最大值的行列索引

4

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

ma <- matrix(1:50, nrow = 5)
which(ma == max(ma), arr.ind = TRUE)

如果我们不仅想要最大值的坐标,而是N个最高值的坐标呢?

比如说:

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

你可以使用例如N=5: lapply(sort(ma, decreasing = T)[1:5], function(x) which(ma == x, arr.ind = TRUE)) - yfyang
一个比下面的答案更简洁和高效的解决方案是:列出(并绘制)矩阵的前k个值 - Zheyuan Li
1个回答

6
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接