title: R: Find missing columns, add to data frame if missing
body: <p>I'd like to write some code that would take a given data frame, check to see if any columns are missing, and if so, add the missing columns filled with 0 or NA. Here's what I've got:</p>
  
  <pre><code>&gt; df
     x1 x2 x4
  1   0  1  3
  2   3  1  3
  3   1  2  1
  
  &gt; nameslist &lt;- c("x1","x2","x3","x4")
  &gt; miss.names &lt;- !nameslist %in% colnames(df)
  &gt; holder &lt;- rbind(nameslist,miss.names)
  &gt; miss.cols &lt;- subset(holder[1,], holder[2,] == "TRUE")
  </code></pre>
  
  <p>Beyond this point, I can't figure out how to add in the missing column ("x3") without hardcoding it. Ideally, I'd want the new, complete data frame to have columns in the same order as nameslist as well.</p>
  
  <p>Any ideas? My current code can be ignored, no problem.</p>