0

I have two dataframes containing information as follows:

> df1:
  X1      X2
Adele    Soul
Cher     Pop
Sting    Rock
Beyonce  R&B

and

> df2:
name    completeName
 B        Beyonce
 A        Adele
 S        Sting
 M        Madonna
 E        Elvis
 C        Cher
 D        Duffy

And I am trying to match them to create new column in df1 to make it look like this:

> df1:
 X1       X2     Name
Adele    Soul     A
Cher     Pop      C
Sting    Rock     S
Beyonce  R&B      B

I have tried with df1 <- df1[order(match(df2$name, df1)), 1] but somehow I cannot get the Name column in the same order as df1$X1.

Any ideas? Preferably in Base R.

I have been applying ideas from other similar question but it doesn't seem to work for me.

Cahidora
  • 143
  • 7
  • 1
    You are matching against the data.frame 'df1' instead of a column in 'df1'. Try with `merge` i.e. `merge(df1, df2, by.x = 'X1', by.y = 'completeName', all.x = TRUE)` – akrun Jun 16 '18 at 16:26
  • It works but the result is not respecting the order of the columns in `df1`. – Cahidora Jun 16 '18 at 16:29
  • It looks like a join operation. Try with `merge` or one of the join functions. Please check the dupe link – akrun Jun 16 '18 at 16:30

0 Answers0