title: How to do multiple operations, ignoring NAs, in R
body: <p>Is there a quick way to run multiple arithmetic operations across data frame variables while ignoring cases with NAs? I've put a simple example below. </p>
  
  <p>It seems I could add intermediary variables or 'if' statements but that seems too convoluted.</p>
  
  <pre><code>d1&lt;-c(2,2,2,2)
  d2&lt;-c(1,1,1,1)
  d3&lt;-c(1,1,NA,NA)
  
  df&lt;-data.frame(d1,d2,d3)
  df
    d1 d2 d3
  1  2  1  1
  2  2  1  1
  3  2  1 NA
  4  2  1 NA
  
  df$d4&lt;-d1*((d2) + (d3))
  df
    d1 d2 d3 d4
  1  2  1  1  4
  2  2  1  1  4
  3  2  1 NA NA
  4  2  1 NA NA
  </code></pre>
  
  <p>What I'd like to get is this:    </p>
  
  <pre><code>df2&lt;-data.frame(d1,d2,d3,d4=c(4,4,2,2))
      df2
        d1 d2 d3 d4
      1  2  1  1  4
      2  2  1  1  4
      3  2  1 NA  2
      4  2  1 NA  2
  </code></pre>
  
  <p>I could replace all values with 0s yet that could also be misleading.</p>
  
  <p>EDIT:</p>
  
  <p>I've tried converting NAs to 0s but it does not work and I don't understand why.</p>
  
  <pre><code>df&lt;-data.frame(d1,d2,d3)
  df
  df[is.na(df)] &lt;- 0
  df
    d1 d2 d3
  1  2  1  1
  2  2  1  1
  3  2  1  0
  4  2  1  0
  df$d4&lt;-d1*((d2) + (d3))
  df
    d1 d2 d3 d4
  1  2  1  1  4
  2  2  1  1  4
  3  2  1  0 NA
  4  2  1  0 NA
  </code></pre>