Home > Enterprise >  Combining cell values of multiple equal dimension matrices to a single matrix with each cell is a li
Combining cell values of multiple equal dimension matrices to a single matrix with each cell is a li

Time:05-31

Input: There are three input matrices of same dimensions 3 input matrices:

              GeneA             GeneB          
GeneA          31                  4           
GeneB           5                  8 

              GeneA             GeneB          
GeneA           5                 14           
GeneB           5                  8 


              GeneA             GeneB          
GeneA          30                 14           
GeneB           45                 7 

output:

                GeneA             GeneB          
GeneA          {31,5,30}         {4,14,14}          
GeneB          {5,5,45}           {8,8,7} 

one matrix with cell value as a list of the values from the input matrices.

CodePudding user response:

You can use mapply, and then assign the structure and dimnames as those from matrix1

matrix(
  mapply(paste, matrix1, matrix2, matrix3, MoreArgs=list(sep=",")), 
  nrow=nrow(matrix1),
  ncol=ncol(matrix1),
  dimnames = dimnames(matrix1)
)

Output:

      GeneA     GeneB    
GeneA "31,5,30" "4,14,14"
GeneB "5,5,45"  "8,8,7"  

CodePudding user response:

You would need to hold each resulting vector within a list in a matrix. If your matrices are called m1, m2 and m3, then you can do:

m <- `dimnames<-`(matrix(lapply(1:4, function(i) c(m1[i], m2[i], m3[i])), 2),
                  dimnames(m1))

So that we have:

m
#>       GeneA     GeneB    
#> GeneA integer,3 integer,3
#> GeneB integer,3 integer,3

and

m[1, 1]
#> [[1]]
#> [1] 31  5 30
  • Related