Error in if/while (condition) { : argument is of length zero

后端 未结 3 890
孤独总比滥情好
孤独总比滥情好 2020-11-28 10:48

I received the error

Error in if (condition) { : argument is of length zero

or

Error in while (condition) { : argument is          


        
3条回答
  •  难免孤独
    2020-11-28 10:48

    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.

提交回复
热议问题