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.
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.
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()!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With