【问题标题】:Matrix indices ordered by the value they contain矩阵索引按它们包含的值排序
【发布时间】:2017-11-23 10:03:39
【问题描述】:

我有一个这样的矩阵:

 mat<-matrix(c(10,45,2,15,3,98,1,7,13),nrow = 3)

mat
     [,1] [,2] [,3]
[1,]   10   15    1
[2,]   45    3    7
[3,]    2   98   13

我想获得有序值的索引,就像我们可以从 order(x, arr.idx = T) 获得但应用于矩阵一样。那就是:

   [,1]  [,2]
     1    3
     3    1
     2    2
     2    3
     1    1
     3    3
     1    2
     2    1
     3    2

有没有快速的方法?

提前谢谢你

【问题讨论】:

    标签: r matrix cell


    【解决方案1】:

    你可以使用

    arrayInd(order(mat), dim(mat), dimnames(mat))
    #      [,1] [,2]
    # [1,]    1    3
    # [2,]    3    1
    # [3,]    2    2
    # [4,]    2    3
    # [5,]    1    1
    # [6,]    3    3
    # [7,]    1    2
    # [8,]    2    1
    # [9,]    3    2
    

    【讨论】:

      【解决方案2】:

      使用order作为索引,我们重新排列'mat'的rowcolcbind它以获得有序值的行/列索引

      i1 <- order(mat)
      cbind(row(mat)[i1], col(mat)[i1])
      #      [,1] [,2]
      #[1,]    1    3
      #[2,]    3    1
      #[3,]    2    2
      #[4,]    2    3
      #[5,]    1    1
      #[6,]    3    3
      #[7,]    1    2
      #[8,]    2    1
      #[9,]    3    2
      

      【讨论】:

        猜你喜欢
        • 2021-04-03
        • 1970-01-01
        • 2021-08-06
        • 2013-07-05
        • 1970-01-01
        • 2018-04-29
        • 2017-05-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多