a <- character()
b <- "SO is great"
any(a == b)
#> [1] FALSE
all(a == b)
#> [1] TRUE
The manual describes ‘any’ like this
Given a set of logical vectors, is at least one of the values true?
So, not even one value in the comparison a == b
yields TRUE.
If that is the case how can ‘any’ return FALSE while ‘all’ returns TRUE? ‘all’
is described as Given a set of logical vectors, are all of the values true?.
In a nutshell: all values are TRUE and none are TRUE at the same time? I am not expert but that looks odd.
Questions:
Is there a reasonable explanation for or is it just some quirk of R?
What are the ways around this?
Created on 2021-01-08 by the reprex package (v0.3.0)
Usually, when comparing a == b
the elements of the shorter vector are recycled as necessary. However, in your case a
has no elements, so no recycling occurs and the result is an empty logical vector.
The results of any(a == b)
and all(a == b)
are coherent with the logical quantifiers for all and exists. If you quantify on an empty range, for all gives the neutral element for logical conjunction (AND) which is TRUE
, while exists gives the neutral element for logical disjunction (OR) which is FALSE
.
As to how avoid these situations, check if the vectors have the same size, since comparing vectors of different lengths rarely makes sense.