# [R] matrix merge, or something else?

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Fri Mar 10 07:26:01 CET 2017

```test2[ , colnames( test1 ) ] <- test1
--
Sent from my phone. Please excuse my brevity.

On March 9, 2017 6:56:13 PM PST, Evan Cooch <evan.cooch at gmail.com> wrote:
>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
>
>test1
>
>              a  b  d
>row1   1  1  0
>row2   1  0 -1
>row3  -1 -1  0
>
>
>test2
>
>             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
>work.
>
>Any suggestions/pointers to the obvious most appreciated.
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help