I received the error
Error in if (condition) { : argument is of length zero
or
Error in while (condition) { : argument is
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
.
See ?NULL
You have to use is.null
‘is.null’ returns ‘TRUE’ if its argument is ‘NULL’ and ‘FALSE’ otherwise.
Try this:
if ( is.null(hic.data[[z]]) ) { print("is null")}
From section 2.1.6 of the R Language Definition
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.
When testing for NULL values, you want to use is.null(hic.data[[z]])
.