Home > OS >  How to sort column names based on values in a column of another dataframe?
How to sort column names based on values in a column of another dataframe?

Time:12-10

I have two dataframes as follows:

df1 <- data.frame (a  = c(1,2,3,4,5),
                  b = c(6,7,8,9,10),
                  x = c(6,7,8,9,10),
                  d = c(6,7,8,9,10),
                  z = c(6,7,8,9,10)
                  )
df1

looks as :

a   b   x   d   z
1   6   6   6   6
2   7   7   7   7
3   8   8   8   8
4   9   9   9   9
5   10  10  10  10

another dataframe df2

df2 = data.frame (km = c("d","z","b","x","a"))

looks as follows:

km
d
z
b
x
a

I want to order the columns of first dataframe as per row values of second dataframe such that output is as follows:

d   z   b   x   a
6   6   6   6   1
7   7   7   7   2
8   8   8   8   3
9   9   9   9   4
10  10  10  10  5

CodePudding user response:

In base R, simply subset the columns of df1 using df2$km:

df1[, df2$km]

Or with dplyr, use select(all_of()):

library(dplyr)

df1 %>%
  select(all_of(df2$km))

Result from either approach:

   d  z  b  x a
1  6  6  6  6 1
2  7  7  7  7 2
3  8  8  8  8 3
4  9  9  9  9 4
5 10 10 10 10 5
  • Related