Sum of two Columns of Data Frame with NA Values

后端 未结 5 612
余生分开走
余生分开走 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:46

    Here is another solution, with concatenated ifelse():

     dat$e <- ifelse(is.na(dat$b) & is.na(dat$c), dat$e <-0, ifelse(is.na(dat$b), dat$e <- 0 + dat$c, dat$b + dat$c))
     #  a  b c d e
     #1 1  2 3 4 5
     #2 5 NA 7 8 7
    

    Edit, here is another solution that uses with as suggested by @kasterma in the comments, this is much more readable and straightforward:

     dat$e <- with(dat, ifelse(is.na(b) & is.na(c ), 0, ifelse(is.na(b), 0 + c, b + c)))
    

提交回复
热议问题