title: R How to find and reorder columns in one table according to column order in another table (tables contain diff number of columns)
body: <p>I have read the following threads that seem to be similar (but still different) questions with mine:</p>
  
  <ol>
  <li><a href="https://stackoverflow.com/questions/11977102/order-data-frame-rows-according-to-a-target-vector-that-specifies-the-desired-or">Order data frame rows according to a target vector that specifies the desired order</a></li>
  <li><a href="https://stackoverflow.com/questions/12232041/how-to-reorder-data-table-columns-without-copying">How to reorder data.table columns (without copying)</a></li>
  </ol>
  
  <p>my questions are different because in thread 1, the two tables have same length, and i tried using method indicated in thread 2, but seems like they also have to be same length.</p>
  
  <p>for illustration purpose, i'll create two tables as following:</p>
  
  <pre><code>table1 = data.frame(rbind(c(rep(c(TRUE,FALSE), 3)), c(rep(TRUE, 4), rep(FALSE, 2))))
  dim(table1)
  setnames(table1, letters[1:6])
  table1
    a     b    c     d     e     f
  1 TRUE FALSE TRUE FALSE  TRUE FALSE
  2 TRUE  TRUE TRUE  TRUE FALSE FALSE
  
  table2 = data.frame(rbind(c(rep(c(TRUE,FALSE), 2)), c(rep(TRUE, 3), rep(FALSE, 1))))
  dim(table2)
  setnames(table2, letters[7:4])
  table2
    g     f    e     d
  1 TRUE FALSE TRUE FALSE
  2 TRUE  TRUE TRUE FALSE
  </code></pre>
  
  <p>the desired return would be:</p>
  
  <pre><code>  f     e      d
  1 FALSE TRUE  FALSE
  2 FALSE FALSE TRUE
  </code></pre>
  
  <p>the return table will fit the following criteria:</p>
  
  <ol>
  <li>contains ONLY the letters exist in BOTH tables</li>
  <li>order of the return table is consistent with the order in table 2</li>
  </ol>
  
  <p><strong>Basically,</strong> I want to clean my table1 to contain only column names that also exist in table2, and i want the table1 columns to be reordered in order same as the columns in table 2.</p>
  
  <p>Let me know if I need to clarify anything else! Thank you!</p>