【问题标题】:How to reorder the rows of one matrix with respect to the other matrix?如何相对于另一个矩阵重新排序一个矩阵的行?
【发布时间】:2014-07-27 19:50:56
【问题描述】:

我有两个不同维度的大矩阵AB。我想相对于矩阵A 的行对矩阵B 的行进行排序。并将值为0 的行添加到矩阵B,如果该行在B 中不存在但在A

这是可重现的示例和预期输出:

A<-matrix(c(1:40), ncol=8)
rownames(A)<-c("B", "A", "C", "D", "E")

> A
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
B    1    6   11   16   21   26   31   36
A    2    7   12   17   22   27   32   37
C    3    8   13   18   23   28   33   38
D    4    9   14   19   24   29   34   39
E    5   10   15   20   25   30   35   40

> B<-matrix(c(100:108),ncol=3)
 rownames(B)<-c("A", "E", "C")

> B
  [,1] [,2] [,3]
A  100  103  106
E  101  104  107
C  102  105  108

这是预期的输出:

>B
      [,1] [,2] [,3]
    B    0    0    0
    A  100  103  106
    C  102  105  108
    D    0    0    0
    E  101  104  107
    > 

有人能帮我在 R 中实现这个吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    来自 sql 背景,这是我首先想到的。其他答案要好得多。

    A1 = cbind(id = rownames(A),as.data.frame(A), stringsAsFactors = FALSE)
    B1 = cbind(id = rownames(B),as.data.frame(B), stringsAsFactors = FALSE)
    AB = merge(A1, B1, by = "id", all = T)
    AB1 = as.matrix(AB[,(dim(A1)[2] + 1) : dim(AB)[2]])
    dimnames(AB1) = NULL
    AB1[is.na(AB1)] = 0
    rownames(AB1) = AB[,1]
    (B = AB1[match(AB[,1],A1[,1]),])
    

    【讨论】:

    • 关于您对pd.np.ptp 的评论...(-:我也对发布该内容感到内疚。但是,我这样做是为了证明一点。有些人觉得导入另一个库很尴尬。我的观点是不是 pandas 已经导入了 numpy。为了证明这一点,我没有导入 numpy,只是使用了pd.np.ptp。不过我在实践中永远不会使用它。
    【解决方案2】:

    另一种方法

    > temp <- A[,seq(ncol(B))]*0            
    > temp[rownames(B), ] <- B            
    > (B <- temp)
    #      [,1] [,2] [,3]
    #B    0    0    0
    #A  100  103  106
    #C  102  105  108
    #D    0    0    0
    #E  101  104  107
    

    【讨论】:

      【解决方案3】:

      一种方法可能是:

      res = as.table(array(0, c(nrow(A), ncol(B)), list(rownames(A), NULL)))
      B2 = as.data.frame(as.table(B))
      res[as.matrix(B2[1:2])] = B2[[3]]
      res  ##which can be converted back to a `colnames`less matrix
      #    A   B   C
      #B   0   0   0
      #A 100 103 106
      #C 102 105 108
      #D   0   0   0
      #E 101 104 107
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-10
        • 1970-01-01
        • 2021-11-09
        • 1970-01-01
        • 2018-04-09
        • 2019-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多