[R] Alternate to for-loop

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Mon Feb 16 20:20:24 CET 2009


Patrick Burns wrote:
> If the goal is to "look" professional, then
> 'replicate' probably suits.  If the goal is to
> compute as fast as possible, then that isn't
> the case because 'replicate' is really a 'for'
> loop in disguise and there are other ways.
>
> Here's one other way:
>
> function (size, replicates, distfun, ...)
> {
>
>        colMeans(array(distfun(size * replicates, ...), c(size,
> replicates)))
> }

a naive benchmark:

f.rep = function(n, m) replicate(n, rnorm(m))
f.pat = function(n, m) colMeans(array(rnorm(n*m), c(n, m)))

system.time(f.pat(1000, 1000))
system.time(f.rep(1000, 1000))

makes me believe that there is no significant difference in efficiency
between the 'professionally-looking' replicate-based solution and the
'as fast as possible' pat's solution.

vQ




More information about the R-help mailing list