3

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

ECII
  • 10,297
  • 18
  • 80
  • 121

3 Answers3

3

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
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
2

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
PaulS
  • 21,159
  • 2
  • 9
  • 26
1

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

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

x <- NA
x %in% 2
#[1] FALSE
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213