Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort the order of columns in a dataframe by another dataframe in R?

Tags:

r

I've received so much help from this site I wanted to share an answer I couldn't find in a similar question. Let's say I have two dataframes:

df1 = data.frame(X1 = c(1:6), X2 = c(rep("A", 3), rep("B", 3)), X3 = c(3:8))
df2 = data.frame(X3 = c(2:7), X1 = c(1:6), X2 = c(rep("C", 3), rep("D", 3)))

And I would like to reorder the columns of df2 according to df1.

I know I can manually sort df2:

df2<-df2[c("X1","X2","X3")]

But my actual dataframe has 30 columns and I don't want to include all the column names. Additionally, I don't want to sort the column order of both dataframes alphabetically because I would like to retain the column order of df1.

like image 582
Anna Avatar asked Aug 10 '17 18:08

Anna


People also ask

How do you order variables in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.


1 Answers

One trick is to use names(df1):

df2<-df2[names(df1)]

And you get an identical set of columns in df2 as in df1- this is very handy if you need to use rbind()!

like image 158
Anna Avatar answered Sep 28 '22 10:09

Anna