[R] Can we get rid of && and ||?
Prof Brian D Ripley
ripley at stats.ox.ac.uk
Thu Apr 13 13:07:18 CEST 2000
On Thu, 13 Apr 2000, GB wrote:
>
> I have some doubts about the implementation of the operators '&&' and
> '||'. I only discuss '&&' here. The reason: One of my students tried
> (slightly simplified here)
>
> > x <- c(0.5, 1.2, -0.8, 0.7)
> > y <- x[(x > 0) && (x < 1)]
> > y
> [1] 0.5 1.2 -0.8 0.7
Where did he get the idea of using && from? Only C programmers are likely
to think of it, and it will do what they expect.
> This was not his intention. He wanted
>
> > y <- x[(x > 0) & (x < 1)]
> > y
> [1] 0.5 0.7
>
> I suggested that his first attempt should render a "syntax error", since
> '&&' only applies to scalar logicals. However, upon reading
More precisely, it takes the first element of a vector (R has no scalars)
and coerces it to logical.
> the documentation, I found that 'a && b' is in fact equivalent to
> 'a[1] & b[1]' (with one exception).
>
> Therefore, '&&' seems to be of little use in R programming. You can
> almost always use '&' instead (This is in sharp contrast to the use of
> & and && in the C programming language). I can only see one
> advantage (admittedly important, though) with '&&'. In
>
> if (is.numeric(x) && min(x) > 0) ..... (Found in MASS3, p. 94)
>
> you avoid 'min(x)' to be evaluated if x is non-numeric. This doesn't
> work with '&', because then both expressions are evaluated before the
> comparison.
That is used a lot in base R.
> Provided there are no other differences, I suggest that either
>
> a) '&&' is made obsolete, and '&' is 'improved' so that b in
> 'a & b' is evaluated only if some component of a is TRUE, or
That would break S compatibility and a lot of correctly written code
(including in R itself).
> b) a warning (or syntax error) is given if '&&' is used with at least
> one non-scalar argument.
That might be worthwhile.
--
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 272860 (secr)
Oxford OX1 3TG, UK Fax: +44 1865 272595
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list