title: How do I sort the order of columns in a dataframe by another dataframe in R?
body: <p>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:</p>
  
  <pre><code>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)))
  </code></pre>
  
  <p>And I would like to reorder the columns of df2 according to df1.</p>
  
  <p>I know I can manually sort df2:</p>
  
  <pre><code>df2&lt;-df2[c("X1","X2","X3")]
  </code></pre>
  
  <p>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.</p>