Treat NA as zero only when adding a number

前端 未结 2 687
栀梦
栀梦 2020-12-30 12:26

When calculating the sum of two data tables, NA+n=NA.

> dt1 <- data.table(Name=c(\"Joe\",\"Ann\"), \"1\"=c(0,NA), \"2\"=c(3,NA))
> dt1
         


        
相关标签:
2条回答
  • 2020-12-30 12:52
    dtsum  <- rbind(dt1, dt2)[, lapply(.SD, function(x) ifelse(all(is.na(x)), as.numeric(NA), sum(x, na.rm=T))), by=Name]
    

    (includes @Arun's suggestion) na.rm=TRUE is very useful to remember

    0 讨论(0)
  • 2020-12-30 13:16

    You can define your own function to act as you want

    plus <- function(x) {
     if(all(is.na(x))){
       c(x[0],NA)} else {
       sum(x,na.rm = TRUE)}
     }
    
    
    rbind(dt1, dt2)[,lapply(.SD, plus), by = Name]
    
    0 讨论(0)
提交回复
热议问题