How to combine 2 variables and ignore NAs

前端 未结 2 386
情书的邮戳
情书的邮戳 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:21

    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.

提交回复
热议问题