Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can all (`all`) be true while none (`any`) are true at the same time?

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:

  1. Is there a reasonable explanation for or is it just some quirk of R?

  2. What are the ways around this?

Created on 2021-01-08 by the reprex package (v0.3.0)

like image 512
Jan Avatar asked Mar 02 '23 19:03

Jan


1 Answers

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.

like image 171
Piotr P. Karwasz Avatar answered Apr 27 '23 10:04

Piotr P. Karwasz