merge data frames reordering columns

I have two data frames (x, y) with same column names. For example, FIRST, NAME1, NAME2, NAME3. I need to merge them by "FIRST" column, but reorder other columns like this: FIRST, NAME1.x, NAME1.y, NAME2.x, NAME2.y, etc.

x
FIRST   NAME1   NAME2   NAME3
q1  xxx xxx xxx
q2  xxx xxx xxx
q3  xxx xxx xxx
q4  xxx xxx xxx

y
FIRST   NAME1   NAME2   NAME3
  q1    yyy yyy yyy
  q2    yyy yyy yyy
  q3    yyy yyy yyy
  q4    yyy yyy yyy

If I create new data frame like this:

df = merge(x,y, by = "FIRST")

I get

FIRST   NAME1.x NAME2.x NAME3.x NAME1.y NAME2.y NAME3.y
   q1   xxx      xxx     xxx     yyy     yyy    yyy
   q2   xxx      xxx     xxx     yyy     yyy    yyy
   q3   xxx      xxx     xxx     yyy     yyy    yyy
   q4   xxx      xxx     xxx     yyy     yyy    yyy

But I want to have the next result:

FIRST   NAME1.x NAME1.y NAME2.x NAME2.y NAME3.x NAME3.y
  q1    xxx      yyy     xxx     yyy     xxx    yyy
  q2    xxx      yyy     xxx     yyy     xxx    yyy
  q3    xxx      yyy     xxx     yyy     xxx    yyy
  q4    xxx      yyy     xxx     yyy     xxx    yyy

Just reordering columns isn't the solution, because in future there will always be x and y with different number of columns.

Upvotes: 0

Views: 942

Answers (2)

r-user
r-user

Reputation: 1

you can use dplyr functions left_join(df1, df2, by = 'FIRST') then use

%>%
select(FIRST, NAME1.x, NAME1.y, NAME2.x, NAME2.y, NAME3.x, NAME3.y)

to reorder. The pipe allows it to happy in one step.

Upvotes: 0

s__
s__

Reputation: 9485

You can consider to reorder the columns after merging them:

df = merge(x,y, by = "FIRST")
df <- data.frame(FIRST = df$FIRST,
                 NAME1.x = df$NAME1.x,
                 NAME1.y = df$NAME1.y, 
                 NAME2.x = df$NAME2.x,
                 NAME2.y = df$NAME2.y, 
                 NAME3.x = df$NAME3.x,
                 NAME3.y = df$NAME3.y)

So you can put the columns in the place you want, with the names you desire.

Upvotes: 1

Related Questions