R: how to combine two matrices according to their column and row names?

Input matrix A

column1 column2 column3 column4 row1 0 1 0 0 row2 0 0 -1 0 row3 1 0 0 -1 

Input Matrix B

  column5 column6 column7 column8 row1 0 1 0 0 row2 0 0 -1 0 row4 1 0 0 -1 

Output Matrix C

  column1 column2 column3 column4 column5 column6 column7 column8 row1 0 1 0 0 0 1 0 0 row2 0 0 -1 0 0 0 -1 0 row3 1 0 0 -1 0 0 0 0 row4 0 0 0 0 1 0 0 -1 

Notes: matrix A and matrixB have the name of an overlapping row. However, the names of all columns are different.

+7
source share
1 answer

You can use merge to do this by specifying the optional parameters by and all :

 #Reading data txt1 <- "column1 column2 column3 column4 row1 0 1 0 0 row2 0 0 -1 0 row3 1 0 0 -1 " txt2 <- "column5 column6 column7 column8 row1 0 1 0 0 row2 0 0 -1 0 row4 1 0 0 -1 " dat1 <- read.table(textConnection(txt1), header = TRUE) dat2 <- read.table(textConnection(txt2), header = TRUE) #Merge them together merge(dat1, dat2, by = "row.names", all = TRUE) 

Will yield

 Row.names column1 column2 column3 column4 column5 column6 column7 column8 1 row1 0 1 0 0 0 1 0 0 2 row2 0 0 -1 0 0 0 -1 0 3 row3 1 0 0 -1 NA NA NA NA 4 row4 NA NA NA NA 1 0 0 -1 

If you want to replace NA with zeros, this should work:

 #Assign to an object zz <- merge(dat1, dat2, by = "row.names", all = TRUE) #Replace NA with zeros zz[is.na(zz)] <- 0 
+19
source

All Articles