title: How do I check to see if certain columns exist and, if not, how to then create them and populate them with zeroes?
body: <p>I have a data frame which I manipulate and whose final form sometimes changes shape depending on whether or not certain values exist.</p>
  
  <p>Once the data frame is processed and in its final form, I wish to reorder the columns into a particular order before writing to .csv.</p>
  
  <p>However, because some of the columns won't always exist, I want to know if it is possible to check which columns exist and of the ones that do, I want them to follow a particular format and the ones that don't to be created and populated with zeroes.</p>
  
  <p>I have one solution which I think is very clunky and could probably be improved significantly: in this example, I am checking to see if the column <code>taken_offline</code> exists within my dataset.  If so, I want the columns to be reordered in a certain way with this column included and if not, I want <code>taken_offline</code> to be created and populated with zeroes whilst still being reordered in the same way.</p>
  
  <p>Ideally, I want to be able to say "here is the order that the columns should be presented in.  If the column doesn't exist, I want to create it and populate it with zeroes".</p>
  
  <p>I appreciate that a good way might be to take a list of column names from my data frame (<code>users</code>) and to then check the column names against the desired column order (listed below).  However, I am unsure how to implement this idea.</p>
  
  <p>How can I do it?</p>
  
  <p>The output columns should be in this order:</p>
  
  <pre><code>"date",
  "storeName",
  "firstName",
  "lastName",
  "conversation-request",
  "conversation-accepted",
  "acceptance_rate",
  "conversation-missed",
  "taken_offline",
  "conversation-already-accepted",
  "total_missed",
  "conversation-declined"
  </code></pre>
  
  <p>My code (checking for the existence of <code>taken_offline</code>):</p>
  
  <pre><code>if("taken_offline" %in% colnames(users_final)){
    users_final &lt;- users_final[, c(
      "date",
      "storeName",
      "firstName",
      "lastName",
      "conversation-request",
      "conversation-accepted",
      "acceptance_rate",
      "conversation-missed",
      "taken_offline",
      "conversation-already-accepted",
      "total_missed",
      "conversation-declined"
    )]
    print("Taken offline occurrences.")
  } else {
    users_final$taken_offline &lt;- 0
    users_final &lt;- users_final[, c(
      "date",
      "storeName",
      "firstName",
      "lastName",
      "conversation-request",
      "conversation-accepted",
      "acceptance_rate",
      "conversation-missed",
      "taken_offline",
      "conversation-already-accepted",
      "total_missed",
      "conversation-declined"
    )]
    print("No taken offline occurrences.")
  }
  </code></pre>