Search code examples
rlogiccomparison

all() function gives TRUE but any() gives FALSE for same comparison


The any() function is descripted with "Given a set of logical vectors, is at least one of the values true?" while the all() function says "Given a set of logical vectors, are all of the values true?" This means that everything that returns TRUE in all() should return TRUE in any(), too. But see here:

all(NULL == "Yes")
[1] TRUE
any(NULL == "Yes")
[1] FALSE

I know that there is the is.null() function which gives same result for all(is.null(NULL)) and any(is.null(NULL)). But is.null() is not what I need to use in my case. I am working on a function which contains user choices. Those choices can be a predefined word or NULL (if no choice is made). Of course I can revalue NULL internally to a word (i.e. "no_choice") but still, why is this happening that any() returns FALSE? Besides, the question is not that much about is.null() since NULL == 1 gives logical(0) same paradox situation is true for:

all(logical(0))
[1] TRUE
any(logical(0))
[1] FALSE

THIS IS A DUPLICATE

Found a question asking same paradox. I can not mark as duplicate (or do not know how).


Solution

  • From the docs, any ignores zero-length objects:

    ...
    zero or more logical vectors. Other objects of zero length are ignored, and the rest are coerced to logical ignoring any class.

    How is this related to NULL == 1?

    If we break this down, we see that NULL == 1 returns a logical(0) which is of length 0.

    length(logical(0))
    [1] 0
    
    

    This is similar to:

    any()
    [1] FALSE
    

    Now, why does all work?

    The value returned is TRUE if all of the values in x are TRUE (including if there are no values), and FALSE if at least one of the values in x is FALSE. Otherwise the value is NA (which can only occur if na.rm = FALSE and ... contains no FALSE values and at least one NA value).

    Note the including if there are no values part.

    Compare this to the part in any's doc entry:

    The value returned is TRUE if at least one of the values in x is TRUE, and FALSE if all of the values in x are FALSE (including if there are no values)

    I think the main point is that since one is comparing NULL with something else, the returned logical vector is empty (i.e. length zero) which affects how the result is dealt with by any/all.