Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - " missing value where TRUE/FALSE needed " [duplicate]

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?

like image 994
user3582590 Avatar asked Nov 19 '14 13:11

user3582590


2 Answers

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"
like image 67
Cath Avatar answered Oct 22 '22 00:10

Cath


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().

like image 29
Nikos Avatar answered Oct 22 '22 01:10

Nikos