Comparison of Values Involving NA in R

Posted on May 10, 2016 in Programming

Things under legendu.net/outdated are outdated technologies that the author does not plan to update any more. Please look for better alternatives.

The best way to compare values containing NA in R is to define customized comparison functions. Here is an example.

equals = function(x1, x2, na_as_na = FALSE, reverse = FALSE) {
    if (reverse) {
        return(!equals(x1, x2, na_as_na, reverse = FALSE))
    }
    if (na_as_na) {
        return(x1 == x2)
    }
    ifelse(
           is.na(x1), 
           ifelse(is.na(x2), TRUE, FALSE), 
           ifelse(is.na(x2), FALSE, x1 == x2)
       )
}