sum non NA elements only, but if all NA then return NA

前端 未结 2 494
时光说笑
时光说笑 2021-01-12 05:25

I think I already got really good answers on the comments, but I will rephrase the question for future reference.

I am trying to sum by groups using data.table. The

相关标签:
2条回答
  • 2021-01-12 06:15

    Using sum_ from hablar

    library(hablar)
    A[, as.numeric(sum_(col2)), .(col1)]
    #   col1 V1
    #1:    A NA
    #2:    B  5
    #3:    C  4
    
    0 讨论(0)
  • 2021-01-12 06:21

    Following the suggestions from other users, I will post the answer to my question. The solution was provided by @sandipan in the comments above:

    As noted in the question, if you need to sum the values of one column which contains NAs,there are two good approaches:

    1) using ifelse:

    A[, (ifelse(all(is.na(col2)), col2[NA_integer_], sum(col2, na.rm = T))), 
      by = .(col1)]
    

    2) define a function as suggested by @Frank:

    suma = function(x) if (all(is.na(x))) x[NA_integer_] else sum(x, na.rm = TRUE)
    
    A[, suma(col2), by = .(col1)]
    

    Note that I added NA_integer_ as @Frank pointed out because I kept getting errors about the types.

    0 讨论(0)
提交回复
热议问题