Home > Blockchain >  R return FALSE when NA when using == operator
R return FALSE when NA when using == operator

Time:12-31

i have an if loop than needs a logical check.

However the check is x==2

so that

> x<-2
> x==2
[1] TRUE

However when

> x<-NA
> x==2
[1] NA

How can I deal with this problem? I use this check within a for loop and the loop stops executing. When x<-NA, then x==2 should return FALSE

CodePudding user response:

You may want to try:

x <- 2
ifelse(is.na(x), FALSE, x == 2)
#> [1] TRUE

x <- NA
ifelse(is.na(x), FALSE, x == 2)
#> [1] FALSE

CodePudding user response:

Use %in% instead of == which may fix this problem.

x <- 2
x %in% 2
#[1] TRUE

x <- NA
x %in% 2
#[1] FALSE

CodePudding user response:

1) First ensure that x is not NA and then AND that with the desired check. If x were NA then it reduces to FALSE & NA and that equals FALSE.

x <- c(1, NA, 2) # test input

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

2) If x is a scalar then this also works because isTRUE(X) is only TRUE if the argument is TRUE and if it is anything else including NA it is FALSE.

x <- 2
isTRUE(x == 2)
## [1] TRUE

x <- 0
isTRUE(x == 2)
## [1] FALSE

x <- NA
isTRUE(x == 2)
## [1] FALSE

2a) or if x is not necessarily a scalar we can modify it like this

x <- c(1, NA, 2) # test input
sapply(x == 2, isTRUE)
## [1] FALSE FALSE  TRUE

2b) or

x <- c(1, NA, 2) # test input
Vectorize(isTRUE)(x == 2)
## [1] FALSE FALSE  TRUE
  • Related