Reputation: 207
I think this is a super easy question, but I can't seem to figure it out.
I have two variables: varA
and varB
.
varA
has values 'a'
and NA
, and varB has values 'b'
and NA
.
I want to combine them into one variable varC
with value 'a'
where varA
is =='a'
and 'b'
where varB
is =='b'
.
I have tried this:
varC <- varA
varC[varB=='b'] <- varB
but I get the error:
Error in [<-.factor(tmp, varB == "b", : NAs are not allowed in subscripted assignments
What am I doing wrong here?
Upvotes: 0
Views: 4808
Reputation: 1494
The condition varB=='b'
will return NA
when varB
is NA
. Use is.na()
to test for NA
. Here is an example:
a <- c(NA, 'a', NA)
b <- c('b', NA, 'b')
c <- a
c[is.na(c)] <- b[is.na(c)]
c
[1] "b" "a" "b"
Upvotes: 1