Open In App

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

Last Updated : 20 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to fix missing values where true/false is needed in R Programming Language.

Why Does This Error Occur?

When we will compare the value with NA(Not available) putting into an “if statement” or “while statement”, then the ”missing value where true/false needed” error occurs is that you are passing an invalid value to “if statement” or “while statement”.  

Example 1: Fixing with variables

How to Reproduce the Error

Here we will get the error because we used the syntax num == NA. We can not compare the value with NA number, this type of statement(If condition) always returns TRUE or FALSE value.

R




num <- "2"
if (num == NA) {
    print("Number is :", NA)
}else{
    print(num)
}


Output:

Error in if (num == NA) {: missing value where TRUE/FALSE needed

How to Fix the Error

We need to use is.na(Value) because it always returns TRUE or FALSE.

R




num <- "2"
if (is.na(num)) {
    print("Number is : NA")
}else{
    print(num)
}


Output:

[1] "2"

Example 2: Fixing with vector

Here we will get the error because we used the syntax vec[l] != NA. We can not compare the value with NA number, this type of statement(If condition) always returns TRUE or FALSE value.

R




vec = c(1, 0, NA)
for (l in 1:length(vec)) {
    if (vec[l] != NA) print(vec[l]);
}


Output:

Error in if (num == NA) {: missing value where TRUE/FALSE needed

You have to use the function is.na for your if statement to work.

R




vec = c(1, 0, NA)
for (l in 1:length(vec)) {
    if (!is.na(vec[l])) print(vec[l])
}


Output:

[1] 1
[1] 0


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads