【问题标题】:Get indices of K smallest or largest elements in each row of a matrix in R获取R中矩阵每一行中K个最小或最大元素的索引
【发布时间】:2012-12-10 15:49:21
【问题描述】:

如何在R中的矩阵的每一行中获取K个最小或最大元素的索引?

例如我有矩阵:

2   3   1  65  2
46  7   9  3   2
9   45  3  5   7
24  65  87 3   6
34  76  54 33  6

我想在每行中获得 2 个最小元素(以任何方式打破平局)的索引矩阵。结果应采用以下格式:

3 1
5 4
3 4
4 5
5 4

我使用sortapplyarrayIndwhich 等尝试了几个命令,但仍然无法获得所需的结果。 欢迎任何帮助。

【问题讨论】:

    标签: r sorting matrix indices


    【解决方案1】:
    apply(mat, 1, which.max)  #.....largest
    apply(mat, 1, which.min)  #.....smallest
    
    t(apply(mat, 1, sort)[ 1:2, ])  # 2 smallest in each row
    
    t(apply(mat, 1, order)[ 1:2, ])  # indices of 2 smallest in each row
    

    除了使用 reduction=TRUE,您还可以将其用于连续两个最大的:

    t(apply(mat, 1, order)[ 5:4, ])    
    

    【讨论】:

    • @DWin 我建议进行编辑以将 decreasing 参数添加到 order 以获得连续 X 个最大/最小元素。
    • @NDThokare 我认为编辑没有通过,所以我会在评论中说出来。要获得最大的 2 个元素,请向 order 添加一个元素:t(apply(mat, 1, order, decreasing=TRUE)[ 1:2, ])
    【解决方案2】:

    怎么样

    • 查找每行中 k 个最大值的索引

      apply(mat, 1, function(x, k) which(x <= max(sort(x, decreasing = F)[1:k]), arr.ind = T), k)`
      
    • 查找每行中 k 个最小值的索引

      apply(mat, 1, function(x, k) which(x >= min(sort(x, decreasing = T)[1:k]), arr.ind = T), k)`
      

    在你的例子中,对于k &lt;- 2,前者的结果是

         [,1] [,2] [,3] [,4] [,5]
    [1,]    2    1    1    2    2
    [2,]    4    3    2    3    3
    

    而后者的结果是

    [[1]]
    [1] 1 3 5
    
    [[2]]
    [1] 4 5
    
    [[3]]
    [1] 3 4
    
    [[4]]
    [1] 4 5
    
    [[5]]
    [1] 4 5
    

    apply 的第二个参数从 1 更改为 2 用于搜索列。

    【讨论】:

      猜你喜欢
      • 2011-02-11
      • 2016-07-09
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      相关资源
      最近更新 更多