Home > database >  R - Merge data from two data frames with different nrow if text condition is met [duplicate]
R - Merge data from two data frames with different nrow if text condition is met [duplicate]

Time:10-01

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?

CodePudding user response:

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")
  • Related