[R] R vs Matlab {Re: R in Industry}

Douglas Bates bates at stat.wisc.edu
Thu Feb 8 18:55:03 CET 2007


On 2/8/07, Manuel Morales <Manuel.A.Morales at williams.edu> wrote:
> On Thu, 2007-02-08 at 16:53 +0100, Martin Maechler wrote:
> > >>>>> "Albr" == Albrecht, Dr Stefan (AZ Private Equity Partner) <stefan.albrecht at apep.com>
> > >>>>>     on Thu, 8 Feb 2007 16:38:18 +0100 writes:
> <snip>
> >     Albr> And, I was very astonished to realise, Matlab is very, very much faster
> >     Albr> with simple "for" loops, which would speed up simulations considerably.
> > Can you give some evidence for this statement, please?
> >
> > At the moment, I'd bet that you use forgot to pre-allocate a
> > result array in R and do something like the "notorious horrible" (:-)
> > 1-dimensional
> >
> >   r <- NULL
> >   for(i in 1:10000) {
> >       r[i] <- verycomplicatedsimulation(i)
> >   }
> >
> > instead of the "correct"
> >
> >   r <- numeric(10000)
> >   for(i in 1:10000) {
> >       r[i] <- verycomplicatedsimulation(i)
> >   }
>
> Would a similar speed issue arise for the construction:
> r <- vector()
> ...

Why not try it and find out?

(The answer is yes.  As Martin indicated the issue is whether the
space for the entire result is allocated before inserting individual
elements of the result.  It is possible to extend a vector beyond its
current length but doing so involves allocating space for the new
vector, copying the current contents and then inserting the new
values.  Doing that tens of thousands of times is slow and wasteful.)



More information about the R-help mailing list