0
votes

I'm looking for ways to merge two matrix with differents size by merging those cells of column that have the same value.

For example the next two matrices:

Matrix 1:

a,  1  
b,  4  
c,  5

Matrix 2:

a,  8  
c,  9

After merging by first column:

a,  1,  8  
b,  4,  NA  
c,  5,  9

Thank you!

1
merge(mat1,mat2,by="V1",all=TRUE)thelatemail
For data.frame, there is also plyr::join which mimics an sql call: join(df1, df2, by = "ID").Jens Tierling

1 Answers

0
votes

'dimname' can be specified then merge() can be used easily.

mat1 <- matrix(c("a","b","c", 1,4,5), ncol=2,
               dimnames = list(c("1", "2", "3"), c("id", "v1")))
mat2 <- matrix(c("a","c", 8, 9), ncol=2,
               dimnames = list(c("1", "2"), c("id", "v2")))

merge(mat1, mat2, by="id", all.x = TRUE)
  id v1   v2
1  a  1    8
2  b  4 <NA>
3  c  5    9

Row dimension names can be omitted as dimnames = list(NULL, c("id", "v1")).