# [R] NA treatment when comparing two vectors

fabien verger fabien.verger at gmail.com
Tue Oct 4 18:51:16 CEST 2016

```Hello,

I want to get the differences when comparing 2 vectors, by pair (element by
element).
I'd like to get TRUEs when:
- the two compared elements are different and non-missing (like `!=` does)
- one element is missing and the other is not missing (unfortunatelly `!=`
gives NA and not TRUE)
Note that I don't want to get TRUEs when both are missing. NA or FALSE are
fine.

Given a and b:
> a <- c(1, 2, 3,  NA, NA)
> b <- c(1, 9, NA, 4 , NA)

The only solution I found is:

> a != b | (is.na(a) != is.na(b))
[1] FALSE  TRUE  TRUE  TRUE    NA

Is there a single function which can do the same?
I searched for other comparison tools but found nothing relevant.

And I would like also to avoid using `!=` because I'm often comparing
floating numbers computed by different algorithms (so rounded differently).

I found identical() interesting (for exemple, !(identical(NA, 99)) gives
TRUE) but the result of !(identical(a, b) is a single logical, not a vector
of logicals.