You do first construct your model into a string,
options = c('Sex', 'Sex/(Age + Eth*Lrn)')
evaluation_str = c()
for(i in c(1:2)){
evaluation_str <- c(evaluation_str, paste0('glm.nb(Days ~ ', options[i], ', data = quine)'))
}
> evaluation_str
[1] "glm.nb(Days ~ Sex, data = quine)" "glm.nb(Days ~ Sex/(Age + Eth*Lrn), data = quine)"
Then use eval()
and parse() function to run a loop, I prefer lapply()
, so I don't need to initiate a vector first as results container.
results <- lapply(c(1:2), function(x){
eval(parse(text=evaluation_str[i]))
})
> results
[[1]]
Call: glm.nb(formula = Days ~ Sex/(Age + Eth * Lrn), data = quine,
init.theta = 1.597990733, link = log)
Coefficients:
(Intercept) SexM SexF:AgeF1 SexM:AgeF1 SexF:AgeF2 SexM:AgeF2 SexF:AgeF3
3.01919 -0.47541 -0.70887 -0.72373 -0.61486 0.62842 -0.34235
SexM:AgeF3 SexF:EthN SexM:EthN SexF:LrnSL SexM:LrnSL SexF:EthN:LrnSL SexM:EthN:LrnSL
1.15084 -0.07312 -0.67899 0.94358 0.23891 -1.35849 0.76142
Degrees of Freedom: 145 Total (i.e. Null); 132 Residual
Null Deviance: 234.6
Residual Deviance: 167.6 AIC: 1093
[[2]]
Call: glm.nb(formula = Days ~ Sex/(Age + Eth * Lrn), data = quine,
init.theta = 1.597990733, link = log)
Coefficients:
(Intercept) SexM SexF:AgeF1 SexM:AgeF1 SexF:AgeF2 SexM:AgeF2 SexF:AgeF3
3.01919 -0.47541 -0.70887 -0.72373 -0.61486 0.62842 -0.34235
SexM:AgeF3 SexF:EthN SexM:EthN SexF:LrnSL SexM:LrnSL SexF:EthN:LrnSL SexM:EthN:LrnSL
1.15084 -0.07312 -0.67899 0.94358 0.23891 -1.35849 0.76142
Degrees of Freedom: 145 Total (i.e. Null); 132 Residual
Null Deviance: 234.6
Residual Deviance: 167.6 AIC: 1093
If you want to check each individual model. You can do so:
> coef <- results[[1]]$coefficients
> coef
(Intercept) SexM SexF:AgeF1 SexM:AgeF1 SexF:AgeF2 SexM:AgeF2 SexF:AgeF3
3.0191882 -0.4754051 -0.7088737 -0.7237349 -0.6148641 0.6284201 -0.3423469
SexM:AgeF3 SexF:EthN SexM:EthN SexF:LrnSL SexM:LrnSL SexF:EthN:LrnSL SexM:EthN:LrnSL
1.1508429 -0.0731245 -0.6789869 0.9435760 0.2389097 -1.3584906 0.7614156