How to Fix in R: missing value where true/false needed


One error you may encounter in R is:

Error in if (x[i] == NA) { : missing value where TRUE/FALSE needed

This error occurs when you compare some value to NA in an if statement in R using the syntax x == NA.

An if statement expects either a TRUE or FALSE value, so you need to use is.na(x) instead because this function always returns TRUE or FALSE.

How to Reproduce the Error

Suppose we attempt to loop through a list of values in a vector in R and print the word “missing” each time there is an NA value in the vector:

#define vector with some missing values
x <- c(2, NA, 5, 6, NA, 15, 19)

#loop through vector and print "missing" each time an NA value is encountered
for(i in 1:length(x)) {
 
 if (x[i] == NA) {
    print('Missing')
  }
}

Error in if (x[i] == NA) { : missing value where TRUE/FALSE needed

We receive an error because we used the syntax x[i] == NA

How to Fix the Error

We need to change the syntax to is.na(x) as follows:

#define vector with some missing values
x <- c(2, NA, 5, 6, NA, 15, 19)

#loop through vector and print "missing" each time an NA value is encountered
for(i in 1:length(x)) {
 
 if (is.na(x[i])) {
    print('Missing')
  }
}

[1] "Missing"
[1] "Missing"

Notice that we don’t receive an error and we’re able to print the word “missing” each time we encounter an NA value in the vector.

Additional Resources

The following tutorials explain how to fix other common errors in R:

How to Fix: NAs Introduced by Coercion
How to Fix: incorrect number of subscripts on matrix
How to Fix: number of items to replace is not a multiple of replacement length

Leave a Reply

Your email address will not be published.