user3933907
user3933907

Reputation: 45

Merging two vectors with an 'or'

I have 2 vectors, each of which has some NA values.

a <- c(1, 2, NA, 3, 4, NA)
b <- c(NA, 6, 7, 8, 9, NA) 

I'd like to combine these two with a result that uses the value from a if it is non-NA, otherwise the value from b.

So the result would look like:

c <- c(1, 2, 7, 3, 4, NA)

How can I do this efficiently in R?

Upvotes: 2

Views: 59

Answers (2)

NPE
NPE

Reputation: 500683

How about:

> c <- ifelse(is.na(a), b, a)
> c
[1]  1  2  7  3  4 NA

Upvotes: 2

David Arenburg
David Arenburg

Reputation: 92302

Try

a[is.na(a)] <- b[is.na(a)]
a
## [1]  1  2  7  3  4 NA

Or, if you don't want to overwrite a, just do

c <- a
c[is.na(c)] <- b[is.na(c)]
c
## [1]  1  2  7  3  4 NA

Upvotes: 1

Related Questions