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

Prof Brian Ripley ripley at stats.ox.ac.uk
Sun May 14 22:26:26 CEST 2006


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




More information about the R-help mailing list