[R] Can we get rid of && and ||?

GB gb at stat.umu.se
Thu Apr 13 12:24:28 CEST 2000


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

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 
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.

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

b) a warning (or syntax error) is given if  '&&'  is used with at least
   one non-scalar argument.

Any objections? 

Göran
----------------------------------------------------------
 Göran Broström                      tel: +46 90 786-5223
 Department of Statistics            
 Umeå University                                         
 SE-90187 Umeå, Sweden              email: gb at stat.umu.se
----------------------------------------------------------

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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