Peter Chung
Peter Chung

Reputation: 1122

R merge dataframes with different columns with order

I have three large data frames below, and want to merge into one data frame with order.

df 1:
First Name  Last Name
John        Langham
Paul        McAuley
Steven      Hutchison
Sean        Hamilton
N           N

df2:
First Name  Wage    Location
John        500     HK
Paul        600     NY
Steven      1900    LDN
Sean        800     TL
N           N       N

df3:
Last Name   Time
Langham     8
McAuley     9
Hutchison   12
Hamilton    7
N           N

desired output:
First Name  Last Name   Wage    Location    Time
John        Langham     500     HK          8
Paul        McAuley     600     NY          9
Steven      Hutchison   1900    LDN         12
Sean        Hamilton    800     TL          7
N           N           N       N           N

I know how to merge df1 and df2 but df1+2 merges to df3 by second column changed the order in desired output, so I want to ask is there any recommendation? Thank you.

Upvotes: 0

Views: 1303

Answers (1)

arvi1000
arvi1000

Reputation: 9592

If you are trying to preserve the order as it appears in df1, create a column to memorialize that order, then use it again to set the order of df3

# record order
df1$original_order <- 1:nrow(df1)

# then do your merges...
# ...

# then restore the df1 order to df3
df3 <- df3[order(df3$original_order),]

If you want you can then also get rid of that column:

df3$original_order <- NULL

Upvotes: 2

Related Questions