create list of vectors in for loop
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