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

Ric*_*ton 8 r r-faq

我收到了错误

Error in if (condition) { : argument is not interpretable as logical
Run Code Online (Sandbox Code Playgroud)

要么

Error in while (condition) { : argument is not interpretable as logical
Run Code Online (Sandbox Code Playgroud)

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

Ric*_*ton 12

评估condition导致R无法解释为合乎逻辑的东西.例如,你可以重现这个

if("not logical") {}
Error in if ("not logical") { : argument is not interpretable as logical
Run Code Online (Sandbox Code Playgroud)

ifwhile条件中,R将零FALSE和非零数字解释为TRUE.

if(1) 
{
  "1 was interpreted as TRUE"
}
## [1] "1 was interpreted as TRUE"
Run Code Online (Sandbox Code Playgroud)

但这很危险,因为返回的计算NaN会导致此错误.

if(sqrt(-1)) {}
## Error in if (sqrt(-1)) { : argument is not interpretable as logical
## In addition: Warning message:
## In sqrt(-1) : NaNs produced
Run Code Online (Sandbox Code Playgroud)

这是更好地总是传递逻辑值作为ifwhile条件.这通常表示包含比较运算符(==等)或逻辑运算符(&&等)的表达式.

使用isTRUE有时可以帮助防止这种错误,但请注意,例如,可能isTRUE(NaN)FALSE也可能不是你想要的.

if(isTRUE(NaN)) 
{
  "isTRUE(NaN) was interpreted as TRUE"
} else
{
  "isTRUE(NaN) was interpreted as FALSE"
}
## [1] "isTRUE(NaN) was interpreted as FALSE"
Run Code Online (Sandbox Code Playgroud)

类似地,字符串"TRUE"/ "true"/ "T""FALSE"/ "false"/ "F"可以用作逻辑条件.

if("T") 
{
  "'T' was interpreted as TRUE"
}
## [1] "'T' was interpreted as TRUE"
Run Code Online (Sandbox Code Playgroud)

同样,这有点危险,因为其他字符串会导致错误.

if("TRue") {}
Error in if ("TRue") { : argument is not interpretable as logical
Run Code Online (Sandbox Code Playgroud)

另请参阅相关错误:

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

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

if (NULL) {}
## Error in if (NULL) { : argument is of length zero

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

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)

  • 防止执行错误可以做的最防御的事情是始终使用`if(isTRUE(cond))`. (3认同)