I want to compare two vectors elementwise to check whether an element in a certain position in the first vector is different from the element in the same position in the second vector.
The point is that I have NA
values inside the vectors, and when doing the comparison for these values I get NA
instead of TRUE
or FALSE
.
Reproducible example:
Here is what I get:
a<-c(1, NA, 2, 2, NA)
b<-c(1, 1, 1, NA, NA)
a!=b
[1] FALSE TRUE NA NA NA
Here is how I would like the !=
operator to work (treat NA
values as if they were just another "level" of the variable):
a!=b
[1] FALSE TRUE TRUE TRUE FALSE
There's a possible solution at this link, but the guy is creating a function to perform the task. I was wondering if there's a more elegant way to do that.
a[is.na(a)] <- 999
. – PauleTRUE
becauseNA
is different (not equal) from 1. @Bazz yes, I thought of that solution and it works too, but I would like to have a more elegant solution without having to make the imputation as I should have to reconvert the values fo NA after the comparison (I have a very large dataset so it's not very practical) – Yehudia<-c(1, NA, 2, 2, NA); b<-c(1, 1, 1, NA, NA); a!=b; [1] FALSE NA TRUE NA NA
– Judie