Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R why does all(numeric(0)) give TRUE whereas any(numeric(0)) gives FALSE?

Tags:

r

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)

like image 665
SKR Avatar asked May 24 '18 03:05

SKR


2 Answers

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).

like image 76
neilfws Avatar answered Oct 01 '22 02:10

neilfws


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.

like image 33
John Coleman Avatar answered Oct 01 '22 02:10

John Coleman