How to combine 2 variables and ignore NAs

前端 未结 2 359
情书的邮戳
情书的邮戳 2021-01-22 21:00

I have some data like these

var1   var2
10     NA
101    NA
NA     86
11     NA
NA     11
NA     61

If one variable is NA then the other one is

2条回答
  •  借酒劲吻你
    2021-01-22 21:18

    rowSums with na.rm = TRUE will do this. (This is your suggested solution really...)

    Assuming your data are in a data.frame DF and your comment

    If one variable is NA then the other one is not, and vice-versa.

    is true.

     DF$var3 <- rowSums(DF[, c('var1','var2')], na.rm = TRUE)
    

提交回复
热议问题