关于r:if / while(条件)中的错误{:缺少需要TRUE / FALSE的值

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

我收到此错误消息:

1
Error in if (condition) { : missing value where TRUE/FALSE needed

要么

1
Error in while (condition) { : missing value where TRUE/FALSE needed

这是什么意思,我该如何预防?


condition的评估结果为NAif条件条件必须具有TRUEFALSE结果。

1
2
if (NA) {}
## Error in if (NA) { : missing value where TRUE/FALSE needed

计算结果可能会偶然发生:

1
2
if(TRUE && sqrt(-1)) {}
## Error in if (TRUE && sqrt(-1)) { : missing value where TRUE/FALSE needed

要测试是否缺少对象,请使用is.na(x)而不是x == NA

另请参阅相关错误:

if / while(condition){:参数长度为零时出错

if / while(条件)错误:参数不可解释为逻辑

1
2
3
4
5
6
7
8
9
if (NULL) {}
## Error in if (NULL) { : argument is of length zero

if ("not logical") {}
## Error: argument is not interpretable as logical

if (c(TRUE, FALSE)) {}
## Warning message:
## the condition has length > 1 and only the first element will be used

我在检查空字符串或空字符串时遇到了这个问题

1
if (x == NULL || x == '') {

改成

1
if (is.null(x) || x == '') {


这适用于"NA"不适用于NA

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