[R] behaviour of all(NULL == c("a", "b"))

Thomas Lumley tlumley at u.washington.edu
Wed Feb 9 18:21:26 CET 2005


On Wed, 9 Feb 2005, Matthias Burger wrote:

>
> Hi all,
>
> I'm a little surprised at
>> NULL == c("a", "b")
> logical(0)
>> all(NULL == c("a", "b"))
> [1] TRUE
>
> Reading the documentation for all() this was not clear for me to be expected.

This is related to the question about sum(numeric(0)) that came up a few 
days ago.

It is conventional in logic that "for all x in X: P(x)" is true when X is 
empty.  A reason why this is a useful convention is that it implies
all(c(x,y)) == all(x) && all(y) is still true when x or y happens to be 
empty.  The converse holds for any():  any(logical(0)) is FALSE. This 
surprises fewer people.

A fairly complete list is

all(NULL) is TRUE
any(NULL) is FALSE
sum(NULL) is 0
prod(NULL) is 1
min(NULL) is Inf
max(NULL) is -Inf

with the last two giving a warning

> Originally the question came up when using
>> match.arg(NULL, c("a", "b"))
> [1] "a"
> where I had thought an error would occur.

I would have assumed "a" would be returned, thinking of match.arg as a way 
to handle default arguments, but I agree it isn't documented, and looking 
at the code it isn't clear what the author thought.

On the other hand, it *is* documented that `arg' must be a character 
string, and NULL isn't a character string. Perhaps you should just use 
pmatch() directly, as the main advantage of match.arg() is its ability to 
look up default arguments, which you don't seem to be using.


 	-thomas




More information about the R-help mailing list