[Rd] Use of all/any

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Oct 26 09:16:03 CEST 2007


all/any coerce their arguments to logical (if possible).  I've added a 
warning in R-devel if coercion is from something other than integer.

This arose because it is easy to make a slip and write all(X) > 0 rather 
than all(X > 0): thanks to Bill Dunlap for bringing that to my attention.
However, it has been useful in detecting quite a few other things:

- indices which had been made double where integer was intended. One 
example from predict.lm was

                 iipiv[ii == 0] <- 0

which was intended to be

                 iipiv[ii == 0L] <- 0L

- uses of lapply where sapply was intended.  Examples are of the form

 	all(lapply(z, is.numeric))

which is applying all() to a list.  One might worry that

 	sapply(z, is.numeric)

will return a list if length(z) == 0 (which it does) and so all() would 
warn, but that is covered by another change, to ignore all length-zero 
arguments (and so avoid the cost of coercion to logical(0)).


I decided not to warn on integer as it is so common.  But at least some of 
these are thinkos.  For example, constructions like

 	all(grep(pattern, x))

occurred scores of times in the R sources.  Since the value of grep() is 
an integer vector of positive indices, this is equivalent to

 	length(grep(pattern, x)) > 0

and when used in a if() condition the '> 0' is not needed.


Some warnings are common from other packages: one is

Warning in any(textLocations) :
   coercing argument of type 'double' to logical

from lattice (and Deepayan Sarkar will fix that shortly).  Quite a few 
others looked familiar but are the result of package authors copying code 
from base R or other packages: if you do that you do need to copy the 
bugfixes too.

-- 
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-devel mailing list