Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Equality while ignoring NAs

Tags:

r

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)
like image 981
Xodarap Avatar asked Jan 23 '13 19:01

Xodarap


People also ask

How to check if two things are equal in R?

setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not.

How do you write not equal to Na in R?

They are always treated as NA when using != . You can test for yourself with, e.g., 1 !=

What does == do in R?

The Equality Operator == Relational operators, or comparators, are operators which help us see how one R object relates to another. For example, you can check whether two objects are equal (equality) by using a double equals sign == .


1 Answers

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
like image 76
mishraP Avatar answered Sep 18 '22 02:09

mishraP