if / while(条件){:缺少需要TRUE / FALSE的值时出错


159

我收到此错误消息:

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

要么

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

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


5
double equals运算符不能容忍NA任何一方。如果我定义:x = NA然后执行一个操作,if (x == NA){ ... }则当解析器检查double equals的左侧时,将在运行时引发此错误。要纠正此错误,请确保条件中的每个变量都不使用NA is.na(your_variable)
埃里克·莱斯钦斯基

Answers:


203

的评估condition结果为NA。该if条件必须有一个TRUEFALSE导致。

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

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

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(条件)错误:参数不可解释为逻辑

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

10

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

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

改成

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

1
Fyi,还有!(length(x) == 1L && nzchar(x))
Frank
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.