[R] create an object list in a loop

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Mon Oct 28 15:55:59 CET 2002


Peter Dalgaard BSA <p.dalgaard at biostat.ku.dk> writes:

> Jake Bowers <jbowers at csm.berkeley.edu> writes:
> 
> > Hi.
> > 
> > How about:
> > 
> > n<-10
> > aval<-list()
> > for(i in 1:n){
> >  aval[[i]]<-matrix(....)
> > }
> > 
> > Then you could access the first matrix as aval[[1]]
> 
> or, 
> 
> aval <- lapply(1:n, function(i) matrix(.....))

Sorry, forgot to say that the construct

 aval<-list()
 for(i in 1:n) aval[[i]]<-.....

is distictly bad since it requires a reallocation of the list every
time you add to it. If you have to do it that way, use 

aval <- vector("list", n)

to create aval with the correct length from the outset. (Of course
this is just another good reason to prefer lapply() ... .)

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list