I was trying to generate a sequence of indices where consecutive 1s appear in a vector and I stumbled upon this peculiar case. Why peculiar, because I don't understand when all()
gives TRUE it means every value is TRUE so any()
should also give TRUE which is not the case here.
all(numeric(0))
# [1] TRUE
any(numeric(0))
# [1] FALSE
Most questions I found concern comparing numeric(0) to a number and how to avoid generating numeric(0)
Since there are a couple of votes for my comment as an answer, I'll post it here.
The documentation ?all
states that (just showing the relevant parts):
The value returned is TRUE [...] (including if there are no values)
And for ?any
, again just the relevant parts:
The value returned is [...] FALSE [...] (including if there are no values)
The functions are defined that way so as other operations works as expected. In particular as @bmrn points out: all(all(x), all(y)) == all(x, y)
.
A similar phenomena occurs with min
and max
:
> min(numeric(0))
[1] Inf
#but
> max(numeric(0))
[1] -Inf
These two computations trigger warnings but not errors. The important question is why they return the values that they return. To answer that, note that another name for the minimum of a finite set is its greatest lowest bound. Everything is a lowest bound for an empty set, so no finite number is the greatest lowest bound, hence it is defined to be infinity. Dual reasoning applies to the maximum, since it is the least upper bound.
In the sense of lattice theory, the only reasonable definition for the join (least upper bound) of the empty set is to be the bottom element of the lattice and the meet (greatest lower bound) to be the top of the lattice. In the case of the extended real numbers, these top and bottom elements are Inf
and -Inf
.
The relationship between this and any
and all
is fairly straightforward: all
is essentially min
applied to truth values. It is a meet operator which when applied to the empty set should give you the top of the lattice, which is TRUE
in the lattice of truth values. Similarly, any
is basically max
applied to truth values. It is a join operator which should when applied to the empty set give the bottom element of the lattice, which is FALSE
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With