Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two data frames with different sizes

Tags:

r

I am working on two data frames with different sizes.

matA : col1 col2 col3
row1   aa    abc   123
row2   cc    dfg   455
row3   ee    efg   345

matB : col1 col4 col5
row1   aa    a1   b1
row2   cc    a2   b2
row3   dd    a3   b3
row4   ee    a4   b4

dim(matA) : 2000 * 3
dim(matB) : 4000 * 3


matC : col1 col2 col3  col4 col5
row1 : aa   abc  123   a1    b1
row2 : cc   dfg  455   a2    b2
row3 : dd   efg  345   a3    b3
row4 : ee   NA   NA    a4    b4

I'd merge two into a combined mat(matC) but size is equal as bigger mat(here matB), which some of not matched rows to mat1 should be just empty or NA in matC.

Wonder how to merge above two data frames?

like image 313
ronaldkelley Avatar asked Dec 27 '22 12:12

ronaldkelley


1 Answers

(Untested!) Read ?merge more carefully ... paying special attention to the all argument.

merge(matA,matB,by="col1",all=TRUE)

Technically (a) these are data frames and not matrices (b) by="col1" is unnecessary here.

like image 124
Ben Bolker Avatar answered Jan 07 '23 09:01

Ben Bolker