Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between vectors _including_ NA

Tags:

r

na

vector

Suppose I have a vector x<-c(1,2,NA,4,5,NA).

I apply some mythological code to that vector, which results in another vector, y<-c(1,NA,3, 4,10,NA)

Now I wish to find out at which positions my two vectors differ, where I count two NAs as being the same, and one NA and a non-NA (e.g. the second element of the two example vectors).

Specifically, for my example, I would like to end up with a vector holding c(2,3,5).

For my use case, I am not content with a vector of logical variables, but obviously I can easily convert (which), so I'll accept that as well.

I have some solutions like:

simplediff<-x!=y
nadiff<-is.na(x)!=is.na(y)
which(simplediff | nadiff)

but it feels like I'm reinventing the wheel here. Any better options?

like image 311
Nick Sabbe Avatar asked Dec 01 '11 10:12

Nick Sabbe


People also ask

How do you find the difference between two vectors?

The difference of two vector x=b−a is formed by placing the tails of the two vectors together. Then, the vector x goes from the head of a to the tail of b.

Is NA meaning in R?

In R, missing values are represented by the symbol NA (not available).

How to use is NA in R?

To check if the value is NA in R, use the is.na() function. The is.na() is a built-in R function that returns TRUE if it finds NA value and FALSE if it does not find in the dataset. If the value is NA, the is.na() function returns TRUE, otherwise, returns FALSE.


1 Answers

How about looping and using identical?

 !mapply(identical,x,y)
[1] FALSE  TRUE  TRUE FALSE  TRUE FALSE

And for positions:

seq_along(x)[!mapply(identical,x,y)]
[1] 2 3 5

or

which(!mapply(identical,x,y))
[1] 2 3 5
like image 92
James Avatar answered Oct 23 '22 04:10

James