我收到了错误
Error in if (condition) { : argument is not interpretable as logical
或
Error in while (condition) { : argument is not interpretable as logical
这是什么意思,我该如何预防?
答案 0 :(得分:11)
对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