Reordering DataFrame Columns to Match Another DataFrame's Sort Order in R

41 Views Asked by At

I have two data frames df1 and df2 containing three columns L, M, and G.

df1 <- data.frame(L= c(0, 1,1,2,2,2,3,3,3,3), M= c(0,0,1,0,1,2,0,1,2,3), G= (1:10))
df2<- data.frame(L=c(0,1,2,3,1,2,3,2,3,3), M= c(0,0,0,0,1,1,1,2,2,3), G= c(12, 13, 4, 6, 7, 54, 87,56,3,0))

Keeping the df1 as it is with no changes. But, I want to reshuffle the L and M of df2 to be the same sort as df1, while keeping the corresponding values of G in df2 intact I want to get the following results

desired_result <- data.frame(L= c(0,1,1,2,2,2,3,3,3,3), M= c(0,0,1,0,1,2,0,1,2,3), G= c(12,13,7,4,54,56,6,87,3,0))
1

There are 1 best solutions below

2
Ronak Shah On

You can do a simple join after removing the G column from df1.

library(dplyr)
  
df1 %>% select(-G) %>% left_join(df2, join_by(L, M)) 

#   L M  G
#1  0 0 12
#2  1 0 13
#3  1 1  7
#4  2 0  4
#5  2 1 54
#6  2 2 56
#7  3 0  6
#8  3 1 87
#9  3 2  3
#10 3 3  0

Equivalent in base R :

indx <- match('G', names(df1))
merge(df1[-indx], df2, all.x = TRUE, by = c("L", "M"))