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

前端 未结 2 506
时光说笑
时光说笑 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: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.

提交回复
热议问题