if/while(条件)中的错误:参数不能解释为逻辑
Posted
技术标签:
【中文标题】if/while(条件)中的错误:参数不能解释为逻辑【英文标题】:Error in if/while (condition) : argument is not interpretable as logical 【发布时间】:2015-02-23 22:13:17 【问题描述】:我收到了错误
Error in if (condition) : argument is not interpretable as logical
或
Error in while (condition) : argument is not interpretable as logical
这是什么意思,我该如何预防?
【问题讨论】:
【参考方案1】:condition
的评估导致了 R 无法解释为合乎逻辑的事情。例如,您可以使用
if("not logical")
Error in if ("not logical") : argument is not interpretable as logical
在if
和while
条件下,R 会将零解释为FALSE
,将非零数字解释为TRUE
。
if(1)
"1 was interpreted as TRUE"
## [1] "1 was interpreted as TRUE"
但这很危险,因为返回 NaN
的计算会导致此错误。
if(sqrt(-1))
## Error in if (sqrt(-1)) : argument is not interpretable as logical
## In addition: Warning message:
## In sqrt(-1) : NaNs produced
最好始终将逻辑值作为if
或while
条件传递。这通常表示包含comparison operator(==
等)或logical operator(&&
等)的表达式。
使用 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"
类似地,字符串"TRUE"
/"true"
/"T"
和"FALSE"
/"false"
/"F"
可以用作逻辑条件。
if("T")
"'T' was interpreted as TRUE"
## [1] "'T' was interpreted as TRUE"
同样,这有点危险,因为其他字符串会导致错误。
if("TRue")
Error in if ("TRue") : argument is not interpretable as logical
另见相关错误:
Error in if/while (condition) : argument is of length zero
Error in if/while (condition) : missing Value where TRUE/FALSE needed
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(isTRUE(cond))
。以上是关于if/while(条件)中的错误:参数不能解释为逻辑的主要内容,如果未能解决你的问题,请参考以下文章