【问题标题】:Error in if/while (condition) : argument is not interpretable as logicalif/while(条件)中的错误:参数不能解释为逻辑
【发布时间】: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

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

【问题讨论】:

    标签: r r-faq


    【解决方案1】:

    condition 的评估导致了 R 无法解释为合乎逻辑的事情。例如,您可以使用

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

    ifwhile 条件下,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
    

    最好始终将逻辑值作为ifwhile 条件传递。这通常表示包含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))
    猜你喜欢
    • 2020-04-27
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多