Re: [R] apply, apply speed vs. traditional looping mechanisms

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Mon 15 May 2006 - 06:26:26 EST

On Sun, 14 May 2006, John Sorkin wrote:

> Can someone tell me why apply (and apply) are faster in performing
> repeated operations than a for (or do) loop? I am looking for a
> technical explanation.

apply() is just a wrapper for a for loop. So it is not faster that at least one implementation using a for loop: it may be neater and easier to understand than an explicit for loop.

I don't understand why you used 'apply' twice here.

lapply() can be faster than a carefully crafted for() loop (since C-level code is more efficient in memory allocation), but its main rationale is clarity (and especially to avoid traps like

ans <- vector("list", n)
for(i in 1:n) ans[[i]] <- fun(i)

if n turns out to be zero or fun(i) to be NULL).

-- 
Brian D. Ripley,                  ripley@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 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Received on Mon May 15 06:30:12 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Mon 15 May 2006 - 08:10:08 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.