简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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