title: R - How to perform arithmetic operations on some but not all variables over rows, omitting NAs
body: <p>Suppose I have a data.frame:</p>
  
  <pre><code>a &lt;- c(1,2,3,4,5)
  b &lt;- c(0,1,NA,3,4)
  c &lt;- c(9,10,11,NA,13)
  
  df &lt;- data.frame(a,b,c)
  </code></pre>
  
  <p>I managed to write a custom function which I can use to sum certain variables over rows, while ignoring NAs (in this case, I sum over all variables, but imagine a big data.frame where I only need to add up a few variables):</p>
  
  <pre><code>sum.df.na.rm &lt;- function(x) {
      rowSums(df[,x], na.rm = TRUE)
  }
  
  df$d &lt;- sum.df.na.rm(c("a","b","c"))
  
  &gt; df
    a  b  c  d
    1  0  9 10
    2  1 10 13
    3 NA 11 14
    4  3 NA  7
    5  4 13 22
  </code></pre>
  
  <p>Now suppose I want to substract b from a, and add c, while still ignoring NAs. I can do:</p>
  
  <pre><code>df$bneg &lt;- df$b * (-1)
  df$e &lt;- sum.df.na.rm(c("a","bneg","c"))
  
  &gt; df
    a  b  c  d bneg  e
    1  0  9 10    0 10
    2  1 10 13   -1 11
    3 NA 11 14   NA 14
    4  3 NA  7   -3  1
    5  4 13 22   -4 14
  </code></pre>
  
  <p>But having to multiply b by (-1) to have it substracted in the <code>sum.df.na.rm</code> function seems very inefficient to me. </p>
  
  <p>How would you do this without the use of the intermediate variable <em>bneg</em>?</p>