Reorder columns based on a variable from another dataset in R

Viewed 24

I need to reorder my dataset columns based on a variable order in another dataset. Here is my sample dataset:

df1 <- data.frame(id_1 = c(1,2,3,4),
                 item_2 = c(2,3,4,5),
                 location_3 = c(3,3,4,6))

> df1
  id_1 item_2 location_3
1    1      2          3
2    2      3          3
3    3      4          4
4    4      5          6

I need to order this df1 dataset based on the order from df2$var2 variable

df2 <- data.frame(var1 = c(1,2,3),
                  var2 = c("location_3","item_2","id_1"))

> df2
  var1       var2
1    1 location_3
2    2     item_2
3    3       id_1

The desired output should be:

> df3
  location_3 item_2 id_1
1          3      2    1
2          3      3    2
3          4      4    3
4          6      5    4

Any ideas?

Thanks!

1 Answers

A possible solution, based on dplyr:

library(dplyr)

df1 %>% relocate(df2$var2)

#>   location_3 item_2 id_1
#> 1          3      2    1
#> 2          3      3    2
#> 3          4      4    3
#> 4          6      5    4
Related