R: choose the one not NA

Viewed 60
a <- c(4,NA,12,16,NA)
b <- c(1,2,3,NA,NA)
result <- c(1,2,3,16,NA)

For two vectors a and b, I want to have the vector result:the min one one-on-one. If it is NA, choose the other one. If both of them are NA, them the element is NA.
For example, for the first element of a and b, 1 is minor then 4,the result of the first element of the vector result is 1. The second element of result is 2 because the second element of a is NA. And the last one of result is NA because both of a and b are NA.

In order to obtain the vector result, what is the code of R?

1 Answers

Do you mean something like this :

a <- c(4,NA,12,16,NA)
b <- c(1,2,3,NA,NA)

dd <- data.frame(a,b)
dd

dd$results <-  ifelse(dd$a<dd$b|is.na(dd$a)|(!is.na(dd$a)&is.na(dd$b)),
                     ifelse(is.na(dd$a),dd$b,dd$a),
                     dd$b)
Related