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

后端 未结 4 1787
我寻月下人不归
我寻月下人不归 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:43

    How about using identical() wrapped in mapply()

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

    Also, if you need to compare results from calculations you could get rid of identical() and go with isTRUE(all.equal()) like so

    mapply(FUN=function(x,y){isTRUE(all.equal(x,y))}, a, b)
    

    which gives the same outcomes, but can better deal with rounding issues. Such as

    a<-.3/3
    b<-.1
    mapply(FUN=function(x,y){isTRUE(all.equal(x,y))}, a, b)
    #[1] TRUE
    
    mapply(identical,a,b)
    #[1] FALSE
    

    I think this last example would mess up a lot of the proposed solutions - but switching to all.equal instead of == would likely work for all of them.

提交回复
热议问题