简体   繁体   English

在R中拆分成对矩阵

[英]Splitting a pairwise matrix in R

I have a matrix in the following way: 我有以下方式的矩阵:

         gene ids  A-B   A-C  A-D  B-C  B-D C-D

          GENE1     0     0    1    1    1   0
          GENE2     1     0    1    1    1   1
          GENE3     1     0    0    0    1   1
          GENE4     0     1    0    0    0   0

and would like to split it as follows:The diagonal values will be empty because the above matrix is a pairwise comparison. 并希望将其拆分如下:对角线值将为空,因为上述矩阵是成对比较。

          Gene1
               A  B   C  D  
           A      0   0  1 
           B   0      1  1
           C   0  1      0
           D   1  1   0

In the same way for all the genes. 对于所有基因都以相同的方式。

I have more than 10000 genes and cannot do it manually. 我有超过10000个基因,无法手动完成。 I tried several things but didn work. 我尝试了几件事,但没有成功。

m <- structure(c(0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0), .Dim = c(4L, 6L), .Dimnames = list(c("GENE1", "GENE2", "GENE3", "GENE4"), c("A-B", "A-C", "A-D", "B-C", "B-D", "C-D")))

gene <- matrix(NA, ncol=4, nrow=4) # empty, template matrix
gene[upper.tri(gene)] <- m[1,]
gene[lower.tri(gene)] <- rev(m[1,])

## gene now contains the interaction matrix for GENE1.

I build on the answer of MrGumble above. 我基于上面MrGumble的答案。 The problem with his solution is that R always has its entries ordered column-major, thus we may fill the lower triangle with the column of data, but not the upper triangle. 他的解决方案的问题在于,R的条目始终按主列排序,因此我们可以用数据列填充下三角,但不填充上三角。 One easy way is just to use the lower part, or to fill the upper part of the matrix with the transpose of the lower. 一种简单的方法是只使用下部,或用下部的转置来填充矩阵的上部。

m <- structure(c(0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0), .Dim = c(4L, 6L), .Dimnames = list(c("GENE1", "GENE2", "GENE3", "GENE4"), c("A-B", "A-C", "A-D", "B-C", "B-D", "C-D")))

gene <- matrix(0, ncol=4, nrow=4) # empty, template matrix
gene[lower.tri(gene)] <- m[4,]
gene <- gene + t(gene)
diag(gene) <- NA

(Made this community wiki, as it is not totally my own answer). (制作此社区Wiki,因为这不是我自己的答案)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM