title: How to safely replace values in data.frame even when data.frame is empty?
body: <p>I'm having trouble writing safe code to manipulate data frames in R. The problem I'm having is that <code>df[...] &lt;- (...)</code> is vulnerable to the data.frame having no rows (among other things!).</p>
  
  <p>Example 1:</p>
  
  <pre><code>df &lt;- data.frame(a = 1:2, b = c(NA, 5))
  df[is.na(df$b), 'b'] &lt;- 0
  </code></pre>
  
  <p>Does what I want - replaces NA with 0.</p>
  
  <p>Example 2: </p>
  
  <pre><code>df.empty &lt;- data.frame(a = character(), b = character())
  df.empty[is.na(df.empty$b), 'b'] &lt;- 0
  df.empty[is.na(df.empty$b), 'b', drop = F] &lt;- 0
  </code></pre>
  
  <p>Both attempts to mutate the data frame in Example 2 result in an error (either replacement has 1 row, data has 0; or 'unused argument (drop = F)).</p>
  
  <p>I find that very annoying.</p>
  
  <p>How do I <strong>universally</strong> mutate a column based on arbitrary (vector) criterion in a data.frame, without having to manually check for all possible conditions like NA, NULL, no rows, coercion to vector because of no rows, etc.? </p>