Search code examples
rdataframedplyr

Reorder column of a dataset based on the order of another dataset in R


I have two dataframes in R,

df1 :

Var1 Val1
A 2
B 3
C 4
D 5

and df2 :

Var1 Val2
D 101
C 103
B 17
A 99

i want to reorder data frame df2 , and more specifically to reorder the order of column var2 of df2 based on the order of the column var1 of df1. Ideally i want my new data frame to look like this :

var2 Val2
A 99
B 17
C 103
D 101

How can i do this in R and if it is possible using dplyr functions ?

data :


library(tidyverse)
df1 = tibble(var1 = c("A","B","C","D"),val1 = c(2,3,4,5))%>%
  mutate(var1 = as.factor(var1))
df2 = tibble(var1 = c("D","C","B","A"),val2 = c(101,103,17,99))%>%
  mutate(var1 = as.factor(var1))



Solution

  • Maybe

    df2 %>%
        arrange(var1[df1$var1])
    

    or

    df2 %>%
        arrange(match(var1, df1$var1))
    

    or

    df1 %>%
        left_join(df2) %>%
        select(-val1)
    

    which gives

    # A tibble: 4 × 2
      var1   val2
      <fct> <dbl>
    1 A        99
    2 B        17
    3 C       103
    4 D       101