user3314181 user3314181 - 3 months ago 10
R Question

Matching elements of two data frames in R

I have two data frames. The first looks like this

name
1 a
2 b
3 c
4 d
5 f


and the second like this

name value
1 b 3
2 d 4
3 f 5
4 a 1
5 c 2
6 k 7
7 m 6


Now I want to add a second column to the first data frame which contains the values of elements taken from the second list. It has to look like this

name value
1 a 1
2 b 3
3 c 2
4 d 4
5 f 5


Can somebody help me this?

Answer

you can use merge to do this. In case your first data frame is called df1 and the second one df2:

merge(df1, df2, by='name')
Comments