[R] Multiple comparisons: its a trap!

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Tue Jul 20 11:08:21 CEST 2004

Liaw, Andy wrote:
> Stupid me: fell into this trap:
>>0 == 0 == 0
> [1] FALSE


  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)


   (A op1 B) and (B op2 C)

If you want:

  (A op1 B) op2 C

you have to put the parens in, and that makes you remember there's some 
Boolean arithmetic going on in there.

This is a nice feature, since we all are used to reading expressions 
like 2 < X < 10, and you can write them like that in Python, and they 
mean what they look like.

You can write like that in R, but beware, its not just 0 == 0 == 0 that 
opens the trap:

  > X = 5
  > 10 < X < 0
  [1] FALSE
  > 0 > X > 10
  [1] TRUE

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


PS oh, and in Perl (0 == 0 == 0) is a syntax error!

More information about the R-help mailing list