1
id1=c('1text','2text','3text')
df1=data.frame(id1)
df1

    id1
1 1text
2 2text
3 3text   



id2=c('2text','3text')
area2=c(11,22)
df2=data.frame(id2,area2)
df2
 id2 area2
1 2text    11
2 3text    22
3 1text    33

I would like to add the data of area2 to the data frame df1 in those rows, where id1=id2, so i have a new column in df1 with the area. It should look like this:

    id1 area1
1 1text    NA
2 2text    11
3 3text    22

Can somebody help?

Maike
  • 43
  • 5

1 Answers1

1

A solution with dplyr:

library(dplyr)

id1=c('1text','2text','3text')
df1=data.frame(id1)

id2=c('2text','3text','1text')
area2=c(11,22,33)
df2=data.frame(id1=id2,area2)

inner_join(df1,df2,by="id1")
PaulS
  • 21,159
  • 2
  • 9
  • 26
  • Thanks, does this also work, if the number of rows differs between df1 and df2? – Maike Sep 30 '21 at 11:33
  • Yes, @Maike, but you have to use `left_join` or `right_join` instead. Please, see: https://dplyr.tidyverse.org/reference/mutate-joins.html – PaulS Sep 30 '21 at 11:38