Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

What causes this error message, and what does it mean?

On further inspection it seems that the value is NULL .

condition
## NULL

In order to deal with this error, how do I test for NULL values?

I expected that this would return TRUE, but I got an empty logical value:

condition == NULL
## logical(0)
  

There is a special object called NULL. It is used whenever there is a need to indicate or specify that an object is absent. It should not be confused with a vector or list of zero length. The NULL object has no type and no modifiable properties. There is only one NULL object in R, to which all instances refer. To test for NULL use is.null. You cannot set attributes on NULL.

What causes this error message, and what does it mean?

if statements take a single logical value (technically a logical vector of length one) as an input for the condition.

The error is thrown when the input condition is of length zero. You can reproduce it with, for example:

if (logical()) {}
## Error: argument is of length zero
if (NULL) {}
## Error: argument is of length zero    

Common mistakes that lead to this error

It is easy to accidentally cause this error when using $ indexing. For example:

l <- list(a = TRUE, b = FALSE, c = NA)
if(l$d) {}   
## Error in if (l$d) { : argument is of length zero

Also using if-else when you meant ifelse, or overriding T and F.

Note these related errors and warnings for other bad conditions:

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

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

if (NA) {}
## Error: missing value where TRUE/FALSE needed
if ("not logical") {}
## Error: argument is not interpretable as logical
if (c(TRUE, FALSE)) {}
## Warning message:
## the condition has length > 1 and only the first element will be used

How do I test for such values?

NULL values can be tested for using is.null. See GSee's answer for more detail.

To make your calls to if safe, a good code pattern is:

if(!is.null(condition) && 
   length(condition) == 1 && 
   !is.na(condition) && 
   condition) {
  # do something

You may also want to look at assert_is_if_condition from assertive.code.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.