Lumos
Lumos

Reputation: 1383

Run all possible models in a r loop

I have 3 independent variables (IV), 1 dependent variable (DV), and an IV group, which the other 5 DVs are nested within. I am exploring the model structures (in Hierarchical Linear Model) by trying out all combinations of the 5 IVs to the models in R. Currently, my method is writing manually the model structures like the following:

glmer(DV ~ IV1 + (1|group), data = df)
glmer(DV ~ IV2 + (1|group), data = df)
glmer(DV ~ IV3 + (1|group), data = df)
glmer(DV ~ IV1 + IV2 + (1|group), data = df)
glmer(DV ~ IV1 + IV3 + (1|group), data = df)
# etc...

How can I elegantly run all possible models in a loop?

Thank you for the help!

Upvotes: 1

Views: 170

Answers (1)

Onyambu
Onyambu

Reputation: 79208

You can also use combinations:

 s=paste0("IV",1:3)
 A=Map(combn,list(s),1:3,c(function(x)reformulate(c(x,"(1|group)"),"D")),simplify=F)
 rapply(A,glmer,data=df)

If you do not care of long line codes, then you can as well include the glmer function in the first line:

 Map(combn,list(s),1:3,c(function(x)glmer(reformulate(c(x,"(1|group)"),"D"),data=df)),simplify=F)

Also you can break the above code into various lines:

s=paste0("IV",1:3)
A=Map(combn,list(s),1:3,c(function(x)paste0(c(x,"(1|group)"),collapse="+")),simplify=F)
B=rapply(A,reformulate,response="D")
lapply(B,glmer,data=df)

I do not recommend breaking it down further, although its possible

Upvotes: 1

Related Questions