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
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)
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.