Statisfaction

Speed up your R code

Posted in R by Julyan Arbel on 27 January 2011

This short post is to share an R tip Pierre recently gave me. When you need to store values sequentially (typically inside a loop), it’s more far efficient to create the whole vector (or matrix) and to fill it, rather than to concatenate the values to your current vector (or matrix). In terms of allocation time, it’s up to 60 times faster

n=10^5
a=NULL
system.time(for (i in 1:n){a=c(a,1)})
>utilisateur     système      écoulé 
>     12.09        0.00       12.09 
 
b=rep(0,n)
system.time(for (i in 1:n){b[i]=1})
>utilisateur     système      écoulé 
>       0.21        0.00        0.20

which makes a big difference. In a Gibbs sampling loop, where a lot of other computations are done, I still have gain of 25%! For other recommendations (don’t use parentheses where you can avoid them), you can have a look on this post.

About these ads
Tagged with: , , ,

4 Responses

Subscribe to comments with RSS.

  1. PAC said, on 27 January 2011 at 20:40

    This could be added to the R programming wikibook, a collaborative handbook for R : http://en.wikibooks.org/wiki/R_Programming/ in the advanced programming page http://en.wikibooks.org/wiki/R_Programming/Advanced_programming

    • Julyan said, on 30 January 2011 at 22:41

      Thanks for that link, I’m often looking for help online.

  2. […] Julyan blogged about allocating memory first before modifying R objects. That’s a very useful trick that applies to most programming […]

  3. […] Speed up your R code […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 53 other followers

%d bloggers like this: