0

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?

beni
  • 180
  • 1
  • 1
  • 8
  • Another option is `setDT(df2)[df1, on = "name"]` from `data.table` – akrun Aug 12 '16 at 08:58
  • If the data.frames contain more columns than the ones in this example and you only want to add the one column to `df1` described in the post, without merging the entire data.frames, you could try `df1$value <- df2$value[match(df1$name,df2$name)]`. – RHertel Aug 12 '16 at 09:20

2 Answers2

2

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')
drmariod
  • 11,106
  • 16
  • 64
  • 110
2

What you want to do is an inner join. You might try with the dplyr package.

library(dplyr)
x <- data.frame(name = c("a", "b", "c", "d", "f"), stringsAsFactors = FALSE)
y <- data.frame(name = c("b", "d", "f", "a", "c", "k", "m"),
                value = c(3, 4, 5, 1, 2, 7, 6),
                stringsAsFactors = FALSE)

joined <- dplyr::inner_join(x, y, by = "name")
kodi1911
  • 662
  • 1
  • 18
  • 34