[R] Multiple comparisons: its a trap!

Gabor Grothendieck ggrothendieck at myway.com
Sun Jul 25 19:15:30 CEST 2004



Peter Dalgaard <p.dalgaard at biostat.ku.dk> writes:
> 
> Barry Rowlingson <B.Rowlingson at lancaster.ac.uk> writes:
> 
> > Liaw, Andy wrote:
> > > Stupid me: fell into this trap:
> > >
> > >>0 == 0 == 0
> > > [1] FALSE
> > >
> >
> > Ouch!
> >
> > Python's comparison operators don't have this trap, since they
> > unravel each comparison pair in a chain so that:
> >
> > (A op1 B op2 C)
> >
> > becomes:
> >
> > (A op1 B) and (B op2 C)
> 
> [chop]
> 
> > Of course old hand Fortran programmers understand all this since the
> > second thing they learnt (after learning how to tap the space bar six
> > times) was the order of precedence of operators...
> 
> SAS does likewise, at least in recent versions. Whether this kind of
> syntactical exceptions is actually helpful is debatable. The problem
> is that you get to teach people that comparisons are binary operators
> except when they are not...
> 
> I wonder how Python actually manages this; doesn't look like something
> that is easy to implement in a yacc-style parser.

Don't know how Python does it but its not the only one and I believe its
often done like this.   Rather than have a Boolean type, NULL is defined
to be false and anything else is true.  If the comparison is TRUE then
the right argument is returned; otherwise NULL is returned.

Thus

	3 < 5 < 6
	==> (3 < 5) < 6
	==> 5 < 6
	==> 6

which is interpreted as TRUE in if statements, etc.  

Note that the 5 is only evaluated once in the above whereas in

        (3 < 5) and (5 < 6)

it would evaluated twice -- not important here but if 5 is replaced
by a function with side effects then it matters.




More information about the R-help mailing list