if/while(condition)中的错误{:缺少需要TRUE/FALSE的值

Dom*_*bey 142 r r-faq

我收到此错误消息:

Error in if (condition) { : missing value where TRUE/FALSE needed
Run Code Online (Sandbox Code Playgroud)

要么

Error in while (condition) { : missing value where TRUE/FALSE needed
Run Code Online (Sandbox Code Playgroud)

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

Bri*_*ggs 188

评估condition结果导致了NA.该if条件必须有一个TRUEFALSE结果.

if (NA) {}
## Error in if (NA) { : missing value where TRUE/FALSE needed
Run Code Online (Sandbox Code Playgroud)

这可能是计算结果意外发生的:

if(TRUE && sqrt(-1)) {}
## Error in if (TRUE && sqrt(-1)) { : missing value where TRUE/FALSE needed
Run Code Online (Sandbox Code Playgroud)

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


另请参阅相关错误:

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

if/while(condition)出错:参数不能解释为逻辑

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
Run Code Online (Sandbox Code Playgroud)


pba*_*tey 9

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

if (x == NULL || x == '') {
Run Code Online (Sandbox Code Playgroud)

改成了

if (is.null(x) || x == '') {
Run Code Online (Sandbox Code Playgroud)