Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

r - How to extend `==` behavior to vectors that include NAs?

I've completely failed at searching for other r-help or Stack Overflow discussion of this specific issue. Sorry if it's somewhere obvious. I believe that I'm just looking for the easiest way to get R's == sign to never return NAs.

# Example #

# Say I have two vectors
a <- c( 1 , 2 , 3 )
b <- c( 1 , 2 , 4 )
# And want to test if each element in the first
# is identical to each element in the second:
a == b
# It does what I want perfectly:
# TRUE TRUE FALSE

# But if either vector contains a missing,
# the `==` operator returns an incorrect result:
a <- c( 1 , NA , 3 ) 
b <- c( 1 , NA , 4 )
# Here I'd want   TRUE TRUE FALSE
a == b
# But I get TRUE NA FALSE

a <- c( 1 , NA , 3 ) 
b <- c( 1 , 2 , 4 )
# Here I'd want   TRUE FALSE FALSE
a == b
# But I get TRUE NA FALSE again.

I get the result I want with:

mapply( `%in%` , a , b )

But mapply seems heavy-handed to me.

Is there a more intuitive solution to this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another option, but is it better than mapply('%in%', a , b)?:

(!is.na(a) & !is.na(b) & a==b) | (is.na(a) & is.na(b))

Following @AnthonyDamico 's suggestion, creation of the "mutt" operator:

"%==%" <- function(a, b) (!is.na(a) & !is.na(b) & a==b) | (is.na(a) & is.na(b))

Edit: or, slightly different and shorter version by @Frank (which is also more efficient)

"%==%" <- function(a, b) (is.na(a) & is.na(b)) | (!is.na(eq <- a==b) & eq)

With the different examples:

a <- c( 1 , 2 , 3 )
b <- c( 1 , 2 , 4 )
a %==% b
# [1]  TRUE  TRUE FALSE

a <- c( 1 , NA , 3 )
b <- c( 1 , NA , 4 )
a %==% b
# [1]  TRUE  TRUE FALSE

a <- c( 1 , NA , 3 )
b <- c( 1 , 2 , 4 )
a %==% b
#[1]  TRUE FALSE FALSE

a <- c( 1 , NA , 3 )
b <- c( 3 , NA , 1 )
a %==% b
#[1] FALSE  TRUE FALSE

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...