[R] lm and loop over variables

Uwe Ligges ligges at statistik.tu-dortmund.de
Mon Nov 21 14:46:17 CET 2011



On 21.11.2011 13:34, Johannes Radinger wrote:
> Hello,
>
> I think I am not to far from a solution. I want to do lm regressions with several variables which I define before in a list. What I've done so far is like:
>
> y<- c(1,5,6,2,5,10) # response
> x1<- c(2,12,8,1,16,17) # predictor
> x2<- c(2,14,5,1,17,17)
> df<- data.frame(y,x1,x2)
>
> predictorlist<- list("x1","x2")
>
> for (i in predictor.list){
> 	model<- lm(y ~ i,data=df)
> 	summary(model)
> }

Sensible or not, to make the loop at least somehow work you need:

for (i in predictorlist){
  model <- lm(paste("y ~", i[[1]]), data=df)
  print(summary(model))
}


Uwe Ligges



> But I don't know I have to pass the variable of the predictors?
>
> Does anyone know how to do that?
>
> /Johannes
> --
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list