Xodarap
Xodarap

Reputation: 11849

R Equality while ignoring NAs

Is there an equivalent of == but with the result that x != NA if x is not NA?

The following does what I want, but it's clunky:

mapply(identical, vec1, vec2)

Upvotes: 22

Views: 10820

Answers (4)

Christoph
Christoph

Reputation: 7063

Why not use base R:

df <- data.frame(col1 = c("a", "b", NA), col2 = 1:3, col3 = 11:13)
df

subset(x = df, subset = col1=="a", select = c(col1, col2))
#   col1 col2
# 1    a    1

or with arrays:

df <- c("a", "b", NA)
subset(x = df, subset = df == "a")

Upvotes: 0

Roman Zenka
Roman Zenka

Reputation: 3604

The == operator is often used in combination with filtering data.frames.

In that situation, dplyr::filter will retain only rows where your condition evaluates to TRUE, unlike [. That effectively implements == but where 1 == NA evalutes as FALSE.

Example:

> df <- data.frame(col1= c("a", "b", NA), col2= 1:3)
> df
       col1 col2
    1    a    1
    2    b    2
    3 <NA>    3

> dplyr::filter(df, col1=="a")
       col1 col2
    1     a    1

Upvotes: 1

mishraP
mishraP

Reputation: 219

Just replace "==" with %in%.

Example:

> df <- data.frame(col1= c("a", "b", NA), col2= 1:3)
> df
       col1 col2
    1    a    1
    2    b    2
    3 <NA>    3

> df[df$col1=="a", ]
       col1 col2
    1     a    1
    NA <NA>   NA

> df[df$col1%in%"a", ]
       col1 col2
    1    a    1

> "x"==NA
  [1] NA

> "x"%in%NA
  [1] FALSE

Upvotes: 20

Justin
Justin

Reputation: 43255

1 == NA returns a logical NA rather than TRUE or FALSE. If you want to call NA FALSE, you could add a second conditional:

set.seed(1)
x <- 1:10
x[4] <- NA
y <- sample(1:10, 10)

x <= y
# [1]  TRUE  TRUE  TRUE    NA FALSE  TRUE  TRUE FALSE  TRUE FALSE

x <= y & !is.na(x)
# [1]  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE

You could also use a second processing step to convert all the NA values from your equality test to FALSE.

foo <- x <= y
foo[is.na(foo)] <- FALSE
foo
# [1]  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE

Also, for what its worth, NA == NA returns NA as does NA != NA.

Upvotes: 12

Related Questions