[R] How to write efficient R code

Rajarshi Guha rxg218 at psu.edu
Tue Feb 17 20:34:04 CET 2004

On Tue, 2004-02-17 at 12:21, Tom Blackwell wrote:
> Lennart  -
> My two rules are:
>   1. Be straightforward.  Don't try to be too fancy.  Don't worry
>   about execution time until you have the WHOLE thing programmed
>   and DOING everything you want it to.  Then profile it, if it's
>   really going to be run more than 1000 times.  Execution time
>   is NOT the issue.  Code maintainability IS.
>  2. Use vector operations wherever possible.  Avoid explicit loops.
>     However, the admonition to avoid loops is probably much less
>     important now than it was with the Splus of 10 or 15 years ago.
> (Not that I succeed in obeying these rules myself, all the time.)
> Remember:  execution time is not the issue.  memory size may be.
> clear, maintainable code definitely is.

I've been using for maybe 6 months or less and am by no means an R
expert. But the above two points are extremely valid - my policy is to
always write code that I can read 2 months later without comments
(though in the end I do add them) - even if it requires loops.

However, after I'm sure the results are right I spend time on trying to
vectorise the code. And that has improved performace by orders of
magnitude (IMO, its also more elegant to have a one line vector
operation rather than a loop).

Of course as I progress towards the status of R expert I hope to be able
to write vectorised code on the fly :)

Rajarshi Guha <rxg218 at psu.edu> <http://jijo.cjb.net>
GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
So the Zen master asked the hot-dog vendor, 
"Can you make me one with everything?"
- TauZero on Slashdot

More information about the R-help mailing list