This question already has an answer here:
这个问题已经有了答案:
- Error in if/while (condition) {: missing Value where TRUE/FALSE needed 2 answers
- if/while (condition){:缺失值,其中TRUE/FALSE需要2个答案
I'm trying to execute the following code in R
我试着用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?
这是怎么回事?
2 个解决方案
#1
17
check the command : NA!=NA
: you'll get the result NA
, hence the error message.
检查命令:NA!=NA:您将得到结果NA,从而得到错误消息。
You have to use the function is.na
for your if
statement to work (in general, it is always better to use this function to check for NA
values) :
你必须使用函数is。为了使ifstatement起作用(一般来说,最好使用此函数检查na值):
comments = c("no","yes",NA)
for (l in 1:length(comments)) {
if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"
#2
4
Can you change the if condition to this:
能否将if条件改为:
if (!is.na(comments[l])) print(comments[l]);
You can only check for NA values with is.na().
只能使用is.na()检查NA值。
#1
17
check the command : NA!=NA
: you'll get the result NA
, hence the error message.
检查命令:NA!=NA:您将得到结果NA,从而得到错误消息。
You have to use the function is.na
for your if
statement to work (in general, it is always better to use this function to check for NA
values) :
你必须使用函数is。为了使ifstatement起作用(一般来说,最好使用此函数检查na值):
comments = c("no","yes",NA)
for (l in 1:length(comments)) {
if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"
#2
4
Can you change the if condition to this:
能否将if条件改为:
if (!is.na(comments[l])) print(comments[l]);
You can only check for NA values with is.na().
只能使用is.na()检查NA值。