【问题标题】:Find row and column index of top values in a matrix查找矩阵中最高值的行和列索引
【发布时间】:2016-04-20 16:28:19
【问题描述】:

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

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))

标签: r matrix


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2013-07-10
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2013-04-20
    • 2015-07-28
    相关资源
    最近更新 更多