if/while(条件)错误:参数不可解释为逻辑 [英] Error in if/while (condition) : argument is not interpretable as logical

查看:265
本文介绍了if/while(条件)错误:参数不可解释为逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了错误

Error in if (condition) { : argument is not interpretable as logical

Error in while (condition) { : argument is not interpretable as logical

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

What does it mean, and how do I prevent it?

推荐答案

condition的求值导致R无法解释为逻辑.您可以使用例如

The evaluation of condition resulted in something that R could not interpret as logical. You can reproduce this with, for example,

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


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


In if and while conditions, R will interpret zero as FALSE and non-zero numbers as TRUE.

if(1) 
{
  "1 was interpreted as TRUE"
}
## [1] "1 was interpreted as TRUE"

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

This is dangerous however, since calculations that return NaN cause this error.

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

最好始终传递逻辑值作为ifwhile条件.这通常意味着包含比较运算符(==,等等)或逻辑运算符(&&等).

It is better to always pass a logical value as the if or while conditional. This usually means an expression that includes a comparison operator (==, etc.) or logical operator (&&, etc.).

使用isTRUE有时可能有助于防止此类错误,但是请注意,例如,isTRUE(NaN)FALSE,可能不是您想要的.

Using isTRUE can sometimes be helpful to prevent this sort of error but note that, for example, isTRUE(NaN) is FALSE, which may or may not be what you want.

if(isTRUE(NaN)) 
{
  "isTRUE(NaN) was interpreted as TRUE"
} else
{
  "isTRUE(NaN) was interpreted as FALSE"
}
## [1] "isTRUE(NaN) was interpreted as FALSE"


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


Similarly, the strings "TRUE"/"true"/"T", and "FALSE"/"false"/"F" can be used as logical conditions.

if("T") 
{
  "'T' was interpreted as TRUE"
}
## [1] "'T' was interpreted as TRUE"

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

Again, this is a little dangerous because other strings cause the error.

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


另请参阅相关错误:


See also the related errors:

if/while(条件)错误{:参数长度为零

if/while(条件)错误:{:缺少需要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

这篇关于if/while(条件)错误:参数不可解释为逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆