Home > Enterprise >  give index based on the common values from two dataframes in R
give index based on the common values from two dataframes in R

Time:10-12

I have two data frames,

df1=data.frame(id=1:4,x1=c(2,3,5,3),x2=c(3,2,3,2),x3=c(3,5,1,3),x4=c(4,3,2,3))

df1
  id x1 x2 x3 x4
1  1  2  3  3  4
2  2  3  2  5  3
3  3  5  3  1  2
4  4  3  2  3  3

df2=data.frame(x1=c(2,5),x2=c(3,3),x3=c(3,1))

df2
  x1 x2 x3
1  2  3  3
2  5  3  1

As you can see, the two rows in df2 have the same values as the row 1 and 3 for x1, x2, and x3 in df1 (with no id and x4). What I want is to add an 'id' column in df2 which contains id 1 and 3. How to do it? Thank you very much.

CodePudding user response:

Does this work:

library(dplyr)

df1 %>% inner_join(df2)
Joining, by = c("x1", "x2", "x3")
  id x1 x2 x3
1  1  2  3  3
2  3  5  3  1

Edited:

cbind(df1['id'], df1[names(df2)]) %>% inner_join(df2)
Joining, by = c("x1", "x2", "x3")
  id x1 x2 x3
1  1  2  3  3
2  3  5  3  1

CodePudding user response:

You can use merge to add missing matching columns.

merge(df2, df1)[,1:4]
#merge(df2, df1, all.x=TRUE)[,1:4] #Alternative
#  x1 x2 x3 id
#1  2  3  3  1
#2  5  3  1  3
  • Related