提问人:Richie Cotton 提问时间:12/27/2014 更新时间:12/27/2014 访问量:49072
if/while(条件)中的错误:参数不可解释为逻辑参数
Error in if/while (condition) : argument is not interpretable as logical
问:
我收到了错误
Error in if (condition) { : argument is not interpretable as logical
或
Error in while (condition) { : argument is not interpretable as logical
这是什么意思,我该如何预防?
答:
14赞
3 revsRichie Cotton
#1
对 的评估导致了 R 无法解释为逻辑的东西。例如,您可以使用以下命令重现此内容:condition
if("not logical") {}
Error in if ("not logical") { : argument is not interpretable as logical
在 和 条件中,R 将把零解释为,将非零数字解释为 。if
while
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
最好始终将逻辑值作为 or 条件传递。这通常意味着包含比较运算符 (, etc.) 或逻辑运算符 (, etc.) 的表达式。if
while
==
&&
有时使用有助于防止此类错误,但请注意,例如,is ,它可能是您想要的,也可能不是您想要的。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
另请参阅相关错误:
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
评论
5赞
Joshua Ulrich
12/27/2014
为了防止执行错误,您可以采取的最防御措施是始终使用 .if(isTRUE(cond))
评论