rvectorlogicnalogical-operators

R method for comparing NAs between two vectors


I am trying to compare two vectors for identical elements, say for vectors a and b below.

# vectors a and b
a <- c(1, 2, 3, NA)
b <- c(1, 3, NA, NA)

# compare for identity
a == b

## [1]  TRUE FALSE    NA    NA

However, I would like the comparison to include NA's, so that when both elements in a given position are NA then the result is TRUE, but if only one is NA then is is FALSE. For that I have written the function below.

# function to include NA's in the comparison
compare_incl_NA <- function(vec1, vec2){
  res = ifelse(is.na(vec1) | is.na(vec2), 
               is.na(vec1) & is.na(vec2), 
               vec1 == vec2)
  res
}

# run function
compare_incl_NA(a,b)

## [1]  TRUE FALSE FALSE  TRUE

It produces the desired output and works fine for my purposes, but I am curious to know whether there is some inbuilt functionality for doing this or, if not, whether the function I have written is the most efficient way of producing this result.


Solution

  • You could use identical along with mapply. For example

    mapply(identical, a, b)
    # [1]  TRUE FALSE FALSE  TRUE