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

前端 未结 1 408
谎友^
谎友^ 2020-12-10 15:35

I received the error

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

or

Error in while (condition) {          


        
1条回答
  •  醉梦人生
    2020-12-10 15:59

    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
    

    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"
    

    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
    

    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.).

    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"
    

    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:

    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
    

    0 讨论(0)
提交回复
热议问题