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

38,895

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
Share:
38,895
Richie Cotton
Author by

Richie Cotton

I'm a Data Evangelist at DataCamp. I wrote a Learning R and Testing R Code. My github and Bitbucket repos, LinkedIn and twitter accounts.

Updated on July 20, 2022

Comments

  • Richie Cotton
    Richie Cotton almost 2 years

    I received the error

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

    or

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

    What does it mean, and how do I prevent it?

  • Joshua Ulrich
    Joshua Ulrich over 9 years
    The most defensive thing you can do to prevent an execution error is to always use if(isTRUE(cond)).