Ajay Shah <[EMAIL PROTECTED]> writes: > This brings me to a question I've always had about "the R way" of > avoiding loops. Yes, the sapply() approach above works. My question > is: Why is this much better than writing it using loops?
It's often not so much a matter of avoiding the loops as such. Splus had a memory-management issue that caused for loops to be extremely slow, but with R it is often a toss-up. The real power of sapply() and friends is that they offer a convenient and compact way of looping *and* collecting results. Compare vectorize <- function(FUN)function(x)sapply(x,FUN) to vectorize <- function(FUN) function(x){ res <- numeric(length(x)) for (i in seq(along=x)) res[i] <- FUN(x[i]) res } and notice that they don't actually do the same thing since sapply is better at adjusting to the return value of FUN. On the other hand, the 2nd version might actually be faster if FUN is know to return numeric values only. -- O__ ---- Peter Dalgaard Blegdamsvej 3 c/ /'_ --- Dept. of Biostatistics 2200 Cph. N (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~~~~~~~~~ - ([EMAIL PROTECTED]) FAX: (+45) 35327907 ______________________________________________ [EMAIL PROTECTED] mailing list https://www.stat.math.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html