In R, if the evaluation of a condition in an if or while statement results in NA, you will raise the error: missing value where TRUE/FALSE needed.
You can solve this error by using is.na(x)
instead of x == NA
.
This tutorial will go through the error in detail and how to solve it with code examples.
Table of contents
Example #1: if missing value where TRUE/FALSE needed with NA
Let’s look at an example where we have a vector that contains a mix of numbers and NA
. We want to append the numbers to a new vector and exclude the NAs.
x <- c(3, 5, NA, 7, NA, 10, NA, 20) y <- vector() for (i in 1:length(x)){ if(x[i] != NA) { y <-(x[i]) } } y
In the above code, we use x[i] != NA
as the condition in an if statement to append to the new vector if the value is not NA. Let’s run the code to see what happens:
Error in if (x[i] != NA) { : missing value where TRUE/FALSE needed
The R interpreter throws the error because an if
conditional must have either a TRUE or FALSE result not NA. The simplest way to reproduce the error is:
if(NA){}
Error in if (NA) { : missing value where TRUE/FALSE needed
Solution
We can solve this error by using is.na(value)
, which will return either TRUE if the value is NA or FALSE if it is not NA. Let’s look at the revised code:
x <- c(3, 5, NA, 7, NA, 10, NA, 20) y <- vector() for (i in 1:length(x)){ if(!is.na(x[i])) { y <- c(y, x[i]) } } y
The condition checks for NOT
NA
by using the exclamation mark. Let’s run the code to see the result:
[1] 3 5 7 10 20
We successfully appended the non-NA
values to the new vector y
.
What is NA in R?
A missing value is an unknown value. In R, missing values are represented by the NA symbol. We can manage NA values using NA functions such as is.na()
and na.omit
.
Summary
Congratulations on reading to the end of this tutorial! The error: missing value where TRUE/FALSE needed occurs when the evaluation of a condition results in a NA instead of either TRUE or FALSE. Solve the error by using is.na()
or use another that condition that evaluates to TRUE or FALSE.
For further reading on R related errors, go to the articles:
- How to Solve R Error: $ operator is invalid for atomic vectors
- How to Solve R Error: object of type ‘closure’ is not subsettable
- How to Solve R Error: object not found
Go to the online courses page on R to learn more about coding in R for data science and machine learning.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.