aliocee
aliocee

Reputation: 730

Merging two data frames with different length and different column level in R

I have a problem merging two data frame with the small data frame being the priority consider the following example please:

d1 
x  y

a  4
b  5
c  9


d2
y  z

5  2
7  8
9  3
4  1
6  8

i want to get same length as the small data frame length if y column of d1 = y column of d2 as shown below:

merged
y  x  z

4  a  1
5  b  2
9  c  3

i wrote the following codes but does not seems to work:

merged   <- merge(d1, d2, by.x="y", by.y="y")

can any one help?

Thank you.

Upvotes: 1

Views: 3373

Answers (1)

Jthorpe
Jthorpe

Reputation: 10204

you can get the 5 rows in the output if you reverse the order of the datasets, as in:

merge(d2, d1, by="y")

You could add the additional column z to d1 via:

d1$z<-d2$z[match(d1$y,d2$y)]

The warning you are getting indicates that there are columns in the two datasets with the same names, which are not not the ones you are matching on. To see the overlap in the field names, use:

intersect(names(d1),names(d2))

(which happens to also be the default value for the argument by).

Upvotes: 1

Related Questions