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

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Feb 9 18:13:23 CET 2005


On Wed, 9 Feb 2005, Matthias Burger wrote:

> I'm a little surprised at
>> NULL == c("a", "b")
> logical(0)

NULL is of length 0.
== coerces arguments and recycles as required, so you have done
as.character(NULL) == character(0)

>> all(NULL == c("a", "b"))
> [1] TRUE
>
> Reading the documentation for all() this was not clear for me to be expected.

all() of a zero-length vector is obviously true as all (zero) elements are 
true, standard in logic.

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

Did you read the help page?  You have misused the function (the first 
argument should be a character string), and it does not say what it does 
in the case of this particular misuse.  This behaviour is different from 
S, which also does not say.

> So could someone please help me and explain what I have overlooked.
> Should I realy have to use is.null() as a precondition check here when a NULL
> argument could arise.

Yes, as the help page says `character string' and NULL is not a character 
string.  The user should ensure the input is as documented.


[I suspect BTW that this undocumented behaviour is intentional, but it was 
introduced in about June 1998 and I cannot find a comment at that time.]


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list