title: sum non NA elements only, but if all NA then return NA
body: <p>I think I already got really good answers on the comments, but I will rephrase the question for future reference.</p>
  
  <p>I am trying to sum by groups using data.table. The problem is that some groups <strong>only</strong> have NA. For these groups I would like the sum to return NA. However, if there is one group that has one value different that NA, I would like to get the sum of the non-NA values.</p>
  
  <pre><code>A &lt;- data.table(col1= c('A','A','B','B','C','C'),  
                  col2= c(NA,NA,2,3,NA,4))
  </code></pre>
  
  <p>This without adding the argument <code>na.rm = T</code>, group C returns NA when it should return 4.</p>
  
  <pre><code>A[, sum(col2), by = .(col1)]
     col1 V1
  1:    A NA
  2:    B  5
  3:    C NA
  </code></pre>
  
  <p>However, adding <code>na.rm = T</code> returns 0 in group A when it should return NA.</p>
  
  <pre><code>A[, sum(col2, na.rm = T), by = .(col1)]
     col1 V1
  1:    A  0
  2:    B  5
  3:    C  4
  </code></pre>
  
  <p>The approach that i like the best is the one that sandipan suggested in the comments, which is akin to the function I wrote below:</p>
  
  <pre><code>ifelse(all(is.na(col2)), NA, sum(col2, na.rm = T)
  </code></pre>
  
  <p>I created a function to get around it, but I am not sure whether there is an already built-in way to get around this:</p>
  
  <pre><code>sum.na &lt;- function(df){
  
    if (all(is.na(df))){
  
      suma &lt;- NA
    }  
    else {    
      suma &lt;- sum(df, na.rm = T)
    }
  
    return(suma)
  }
  </code></pre>