Speed up your R code

January 26, 2011
By

(This article was first published on Statisfaction » R, and kindly contributed to R-bloggers)

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.


To leave a comment for the author, please follow the link and comment on his blog: Statisfaction » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , ,

Comments are closed.