Skip to content

avoiding "for()" loops: a question?

2 messages · Brett Magill, Brian Ripley

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

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])

with this:

sapply(1:dim(x)[2], function(y) my.function (x[,-y] ))

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?
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
On Fri, 2 Aug 2002, Brett Magill wrote:

            
It's much less true in (current) R than in some other S implementations.
(S-PLUS 3.0 to 3.3 in particular.)
That doesn't actually do anything unless my.function has side effects
(very undesirable).
That returns a result.
See `S Programming' for some real examples in different S dialects,
including R from 1999.