[R] matrix merge, or something else?

Evan Cooch evan.cooch at gmail.com
Fri Mar 10 03:56:13 CET 2017

Suppose I have the following two matrices, both with same number of rows 
(3), but different number of columns (3 in test1, 4 in test2).

test1 <- matrix(c(1,1,0,1,0,-1,-1,-1,0),3,3,byrow=T);
test2 <- matrix( rep( 0, len=12), nrow = 3)

I label the rows and columns of the two matrices as follows:

rownames(test1) <- c("row1","row2","row3")
rownames(test2) <- c("row1","row2","row3")

colnames(test1) <- c("a","b","d")
colnames(test2) <- c("a","b","c","d")

So, if we look at the matrices, we see


              a  b  d
row1   1  1  0
row2   1  0 -1
row3  -1 -1  0


             a b c d
row1  0 0 0 0
row2  0 0 0 0
row3  0 0 0 0

So, we see that while both matrices have the same rows, the matrix test1 
has a subset of the columns of test2. In test1, there is no column for 
'c' -- have columns for 'a', 'b', 'd'.

Now, what I want to do is this -- take the information from each column 
in test1, and substitute it into the same row/column in test2. The end 
result should be a matrix that looks like:

             a  b  c  d
row1  1  1  0  0
row2  1  0  0 -1
row3 -1 -1 0   0

My initial though  was some sort of merge by row and column, with some 
funky sort of intersection, but I couldn't figure out how to get that to 

Any suggestions/pointers to the obvious most appreciated.

More information about the R-help mailing list