R - " missing value where TRUE/FALSE needed "

171,868

Solution 1

check the command : NA!=NA : you'll get the result NA, hence the error message.

You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

comments = c("no","yes",NA)
for (l in 1:length(comments)) {
    if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"

Solution 2

Can you change the if condition to this:

if (!is.na(comments[l])) print(comments[l]);

You can only check for NA values with is.na().

Share:
171,868
user3582590
Author by

user3582590

Updated on July 09, 2022

Comments

  • user3582590
    user3582590 almost 2 years

    I'm trying to execute the following code in R

    comments = c("no","yes",NA)
    for (l in 1:length(comments)) {
        if (comments[l] != NA) print(comments[l]);
    }
    

    But I'm getting an error

    Error in if (comments[l] != NA) print(comments[l]) : missing value where TRUE/FALSE needed
    

    What's going on here?