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

From: Prof Brian Ripley <>
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,        
Professor of Applied Statistics,
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________ mailing list
PLEASE do read the posting guide!
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 Please read the posting guide before posting to the list.