Skip to content
Back to formatted view

Raw Message

Message-ID: <06F4FDC1-D96E-4B50-A63E-2CFD43C29E6A@gmail.com>
Date: 2016-12-06T12:33:35Z
From: Peter Dalgaard
Subject: create list of vectors in for loop
In-Reply-To: <CA+8X3fVWEvNRuZu5OcuN4JSsjRrVn4Q4m13vo_+gqhTTC=-1aA@mail.gmail.com>

On 06 Dec 2016, at 11:17 , Jim Lemon <drjimlemon at gmail.com> wrote:

> Hi Paul,
> The easy to understand way is:
> 
> n <- c(1:10)
> # Create empty list to store vectors
> list_of_vecs <- list()
> 
> # Create n vectors of random numbers - length 10. This works ok.
> for (i in n){
> list_of_vecs[[i]]<-rnorm(10,0,1)
> }

As a principle, you want 

  list_of_vecs <- vector("list", 10)

to avoid extending the list on each iteration.


However, a simpler way is

replicate(10, rnorm(10), simplify=FALSE)

(where the simplify bit prevents conversion to 10x10 matrix)

or 

lapply(1:10, function(i) rnorm(10))



-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com