[R] if(foo == TRUE) .. etc

Achim Zeileis Achim.Zeileis at wu-wien.ac.at
Wed Apr 20 14:42:13 CEST 2005


On Wed, 20 Apr 2005 14:30:49 +0200 Martin Maechler wrote:

> >>>>> "Andy" == Andy Bunn <abunn at whrc.org>
> >>>>>     on Tue, 19 Apr 2005 10:27:04 -0400 writes:
> 
>     .....
>     Andy> is.tuesday <- as.POSIXlt(Sys.time())$wday == 2
>     Andy> if (is.tuesday == T) { ....}
>     .....
> 
> aaah, this really hurts my eyes or rather the brain behind! 

Martin, I thought the same when I saw the code yesterday...but was too
busy to write a good reply.

> And it's by far not the first such instance...

The fortunes have:

R> fortune("logical")

Ted Harding: But you can also do these with 'any' and 'all', e.g.
any(v==TRUE).
Thomas Lumley: or any( (v==TRUE)==TRUE), or
any( ((v==TRUE)==TRUE)==TRUE)... Or, perhaps, any(v). Lewis Carroll
wrote a nice piece on this theme. 
   -- Ted Harding and Thomas Lumley (about implementing an `or' of a
      logical vector)
      R-help (August 2004)

> Rather use  " if (is.tuesday) { .... } "
> 
> More generally, please, please, everyone :
> 
>  Replace
> 		if (something == TRUE)
> 	with    if (something)
>  and
> 		if (something.or.other == FALSE)
> 	with    if (!something.or.other)
> 
> {and even more for cases where you have 
>  'T' and 'F' instead of 'TRUE' and 'FALSE' - 
>  which is against all recommendations, since
>   F <- TRUE
>   T <- FALSE
>  are valid statements, probably not common, but think what
>  happens when you accidentally have the equivalent of "T <- 0"
>  somewhere in your global enviroment!

This does not have to be accidentally. `T' is a very common symbol for
the sample size in time series econometrics. So when you implement some
formula from a textbook, it is very tempting to do something like
  T <- nrow(my.ts.object)
I was bitten by this back in the last millenium when there were still
colleagues that used S-PLUS and I gave them some code written for R
(0.6.x, I guess) which had something like the above. Worked perfectly in
R and gave an error in the fast fourier transform (which I never called
in the code!) in S-PLUS...:-)
Z

> }
> 
> Martin Maechler, ETH Zurich
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list