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 NA
s 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?
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.
In R, missing values are represented by the symbol NA (not available).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With