Question

I've seen a few questions asked about this, but I wasn't able to understand any of the answers and they all seem to be closed threads.

What I'm looking to do is join two matrices which have different dimensions, but have two common columns. If any two rows in the two matrices have the same values in two columns I want to then append those two rows, otherwise I want to add the row to the bottom of the matrix.

For example: Matrix 1

Matrix 1
Col1 Col2 Col3 Col4
a     b    c    d
e     f    g    h
i     j    k    l

Matrix 2
Col1 Col3 Col5
a    c    e
g    f    m

In the above example, the first row in Matrices 1 and two have the same entries in Col1 and Col3, while rows 2 and 3 are dissimilar.

I would like the output to look as follows:

NewMatrix
Col1 Col2 Col3 Col4 Col5
a     b   c    d    e
e     f   g    h    0
i     j   k    l    0
g     0   f    0    m

So that the matching rows are joined, while any rows that don't match are simply added on to the end.

Would anyone have an idea of how to do this? Any help would be appreciated.

Thanks

Mike

Was it helpful?

Solution

a <- merge(Matrix1, Matrix2, 
           by.Matrix2 = c(Matrix2[,1], Matrix2$[,3]),
           by.Matrix1 = c(Matrix1[,1], Matrix1[,3]),
           all = TRUE)

Update, much cleaner version from @Ananda:

a <- merge(Matrix1, Matrix2, by = c("Col1", "Col3"), all = TRUE)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top