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.

*Related*

To

**leave a comment** for the author, please follow the link and comment on their blog:

** Statisfaction » R**.

R-bloggers.com offers

**daily e-mail updates** about

R news and

tutorials on topics such as:

Data science,

Big Data, R jobs, 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:** Gibbs, R, system.time, Tip