Sum of two Columns of Data Frame with NA Values

后端 未结 5 617
余生分开走
余生分开走 2020-12-05 10:33

I have a data frame with some NA values. I need the sum of two of the columns. If a value is NA, I need to treat it as zero.

a  b c d
1  2 3 4
5 NA 7 8
         


        
5条回答
  •  被撕碎了的回忆
    2020-12-05 10:53

    if you want to keep NA if both columns has it you can use:

    Data, sample:

    dt <- data.table(x = sample(c(NA, 1, 2, 3), 100, replace = T), y = sample(c(NA, 1, 2, 3), 100, replace = T))
    

    Solution:

    dt[, z := ifelse(is.na(x) & is.na(y), NA_real_, rowSums(.SD, na.rm = T)), .SDcols = c("x", "y")]
    

    (the data.table way)

提交回复
热议问题