[R] Multiple comparisons: its a trap!

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Mon Jul 26 01:09:26 CEST 2004


On 25-Jul-04 Gabor Grothendieck wrote:
> 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.

This is weird, and I'm not sure what is being discussed here.

I had been hanging fire on this, to see what others say. Not having
seen anyone else say what I'd thought originally, here it is.

If you write, in R,

  3 < 5 < 6

you get TRUE. I understand this to be parsed as "(3 < 5) < 6",
not as "(3 < 5) and (5 < 6)". Am I right?

If so, then what happens depends on what "(3 < 5)" evaluates to.
In R, this is TRUE, and in R it is the case that "TRUE < 6":

  > 3<5<6
  [1] TRUE
  > 3<5
  [1] TRUE
  > TRUE<6
  [1] TRUE

However, in R it is also the case that

  > 3<5<4
  [1] TRUE

since

  > TRUE<4
  [1] TRUE

the point being, as I understand it, that in a numerical context

  TRUE = 1

e.g.

  > TRUE + 3
  [1] 4

and, since 1 < 4, "TRUE < 4" is TRUE and so "3 < 5 < 4" is TRUE.

However,

  > 0.3 < 0.5 < 0.6
  [1] FALSE

for precisely the same reason.

So there should be no problem so long as you remember to bear in
mind what values binary comparisons have, following evaluation.

Best wishes to all,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 167 1972
Date: 26-Jul-04                                       Time: 00:09:26
------------------------------ XFMail ------------------------------




More information about the R-help mailing list