How to combine 2 variables and ignore NAs

前端 未结 2 358
情书的邮戳
情书的邮戳 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)
    
    0 讨论(0)
  • Various methods exist. Here's one way:

    var3 <- ifelse(!is.na(var1),var1,var2)
    

    Here it is working on your example:

      var1 <- c(10,101,NA,11,NA,NA)
      var2 <- c(NA,NA,86,NA,11,61)
    
      var3 <- ifelse(!is.na(var1),var1,var2)
    
     > var3
     [1]  10 101  86  11  11  61
    

    This method is relatively general - it works with non-numeric data for example:

      var1 <- c("AB","WZ",NA,"MN",NA,NA)
      var2 <- c(NA,NA,"QT",NA,"MN","RS")
    
      var3 <- ifelse(!is.na(var1),var1,var2)
    
     > var3
     [1] "AB" "WZ" "QT" "MN" "MN" "RS"
    

    The suggestion of replacing NA with 0 and adding wouldn't work in that case.

    0 讨论(0)
提交回复
热议问题