9

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?

user3582590
  • 187
  • 2
  • 4
  • 13

2 Answers2

22

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"
Cath
  • 23,906
  • 5
  • 52
  • 86
5

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

Nikos
  • 3,267
  • 1
  • 25
  • 32
  • 2
    @user3582590: please consider accepting answers that actually answer your question, by clicking the little checkmark under the vote count of the answer. This identifies the most helpful answers for future readers. – Stephan Kolassa Nov 19 '14 at 13:53