[R] a < b < c is alway TRUE
Thomas Lumley
tlumley at u.washington.edu
Fri Jul 6 17:29:33 CEST 2001
On Fri, 6 Jul 2001, Duncan Murdoch wrote:
> In R like C, FALSE is 0 and TRUE is 1. This is a bad thing, but it's
> too late to change it now. With that substitution, all the results
> look reasonable: 0>1, 1<1 and 1>1 are all false, but 0<1 is true.
>
> Why a bad thing? Because it leads to absurdities like this whole
> thread has been discussing!
>
> What should they have done? They should have done what Fortran,
> Pascal, etc. do, and have a separate logical or boolean type that
> isn't automatically converted to a numerical type. In Pascal for
> instance, "3 < 2 < 1" is flagged as a syntax error, because you can't
> compare a boolean to an integer. If you really want to do the weird
> comparison that R is doing, you need to enter it as "ord(3 < 2) < 1",
> and any reader will see that you're doing something weird.
Well, actually R does have a separate logical type for precisely this
reason. That's why, say
2+2==4
evaluates to TRUE in R, not to 1, and why logical subscripts are different
from integer subscripts
For example
x[is.na(x)]
returns the non-missing elements of x, but x[as.numeric(is.na(x))] returns
as many copies of the first elements as there are missing elements.
The feature/bug/wart in R that causes this whole discussion is that
numerical operators in R try to coerce their arguments to numbers, so that
if a or b is logical in
a<b
we actually evaluate
as.numeric(a)<as.numeric(b)
Also, we coerce going the other way in if() statements, to make
if(length(x))
work. This latter coercion is relatively recent and was done for
compatibility with C programmers writing in S.
Certainly a<b<c has no sensible use: if c is numeric it is nonense and if
c is logical it is c & !(a<b). I would even contend that it is a bad sign
if you know what
3<2<1
will evaluate to without careful thought or testing on a copy of R.
-thomas
Thomas Lumley Asst. Professor, Biostatistics
tlumley at u.washington.edu University of Washington, Seattle
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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