[R] loop with variable names

paolo brunori paolo.brunori at uniba.it
Fri Nov 4 17:53:44 CET 2016


Suppose I have the following data:

y<-rnorm(10)
age<-rnorm(10)
sex<-rbinom(10,1, 0.5)
edu<-round(runif(10, 1, 20))
edu2<-edu^2

df<-data.frame(y,age,sex,edu,edu2)

I want to run a large number of models, for example:

lm(y~age)
lm(y~age+sex)
lm(y~age+sex+edu)
lm(y~age+sex+edu+edu2)
lm(y~sex+edu2)
lm(y~age+edu+edu2)
....

But I would like to first define a list containing all possible sets of 
regressors, and then execute each one in a loop/lapply. Unfortunately I 
got lost in trying to paste variables' name in the formula with no result.

many thanks in advance.

paolo



-- 
Paolo Brunori
Ricercatore in Economia Politica & Life Course Centre Fellow
Dipartimento di Scienze Economiche - Università di Bari
www.uniba.it/docenti/brunori-paolo
www.equalchances.org
www.lifecoursecentre.org.au



More information about the R-help mailing list