[R] avoiding "for()" loops: a question?
ripley@stats.ox.ac.uk
ripley at stats.ox.ac.uk
Fri Aug 2 22:30:54 CEST 2002
On Fri, 2 Aug 2002, Brett Magill wrote:
> I have read in several places that one should attempt to avoid for loops
> whenever possible. In this spirit, I was playing with some code that I have
> written to improve its efficiency and elegance.
It's much less true in (current) R than in some other S implementations.
(S-PLUS 3.0 to 3.3 in particular.)
> The following iteratively drops a column from a data frame and applies a
> function to the reminaing columns. I replaced this for loop:
>
> for (y in 1:dim(x)[2]) my.function (x[,-y])
That doesn't actually do anything unless my.function has side effects
(very undesirable).
> with this:
>
> sapply(1:dim(x)[2], function(y) my.function (x[,-y] ))
That returns a result.
> in an attempt to aviod "for()".
>
> However, using system.time() to compare performance of the two functions shows
> no difference in performance over 30 trials with each function on a 500 X 24
> matrix (any edge seems in favor of the for loop). (Win 98,PIII,128M,R 1.5.1)
>
> Is the issue with the way I used sapply? Is there a better way to do this?
See `S Programming' for some real examples in different S dialects,
including R from 1999.
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272860 (secr)
Oxford OX1 3TG, UK Fax: +44 1865 272595
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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