[R] avoiding "for()" loops: a question?
Brett Magill
bmagill at earthlink.net
Fri Aug 2 22:12:12 CEST 2002
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list