I would put the results in a list and avoid the for loop
and assign
statements
You can use a combination of reformulate
and update
to create your formula
orig_formula <- MonExp_EGM~ Month2+Month3+Month4+Month5+Month6+Month7+Month8+Month9+
Month10+Month11+Month12+Yrs_minus_2004 + as.factor(LGA)
te_variables <- paste0('TE_', 1:96)
# Or if you don't have a current version of R
# te_variables <- paste('TE', 1:96, sep = '_')
new_formula <- lapply(te_variables, function(x,orig = orig_formula) {
new <- reformulate(c(x,'.'))
update(orig, new)})
## it works!
new_formula[[1]]
## MonExp_EGM ~ TE_1 + Month2 + Month3 + Month4 + Month5 + Month6 +
## Month7 + Month8 + Month9 + Month10 + Month11 + Month12 +
## Yrs_minus_2004 + as.factor(LGA)
new_formula[[2]]
## MonExp_EGM ~ TE_2 + Month2 + Month3 + Month4 + Month5 + Month6 +
## Month7 + Month8 + Month9 + Month10 + Month11 + Month12 +
## Yrs_minus_2004 + as.factor(LGA)
models <- lapply(new_formula, lm, data = pokies)
There should now be 96 elements in the list models
You can name them to reflect your originally planned nnames
names(models) <- paste0('z.out', 1:96)
# or if you don't have a current version of R
# names(models) <-paste('z.out', 1:96 ,sep = '' )
and then access a single model by
models$z.out5
etc
or create summaries of all of the models
summaries <- lapply(models, summary)
etc....
# just the coefficients
coefficients <- lapply(models, coef)
# the table with coefficient estimates and standard.errors
coef_tables <- apply(summaries, '[[', 'coefficients')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…