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

后端 未结 4 1786
我寻月下人不归
我寻月下人不归 2020-12-09 07:50

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 lo

4条回答
  •  悲&欢浪女
    2020-12-09 08:47

    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
    

提交回复
热议问题