[R] Fitting models in a loop

Peter Dalgaard p.dalgaard at biostat.ku.dk
Tue Aug 1 12:07:11 CEST 2006


"Gesmann, Markus" <Markus.Gesmann at lloyds.com> writes:

> Murray,
> 
> How about creating an empty list and filling it during your loop:
> 
>  mod <- list()
>  for (i in 1:6) {
> 	mod[[i]] <- lm(y ~ poly(x,i))
> 	print(summary(mod[[i]]))
> 	}
> 
> All your models are than stored in one object and you can use lapply to
> do something on them, like:
>  lapply(mod, summary) or lapply(mod, coef)

Ouch. Make that 

mod <- vector("list",6)

Otherwise you'll be extending the vector on every pass through the
loop. 

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list