使用R在回归中循环通过协变量

使用R在回归中循环通过协变量,r,loops,for-loop,regression,R,Loops,For Loop,Regression,我正在尝试运行96个回归,并将结果保存为96个不同的对象。更复杂的是,我希望模型中一个协变量的下标也改变96次。我几乎解决了这个问题,但不幸的是我遇到了麻烦。到目前为止的代码是 for(i in 1:96){ assign(paste("z.out", i,sep=""), lm(rMonExp_EGM~ TE_i + Month2+Month3+Month4+Month5+Month6+Month7+Month8+Month9+ Month10+Month11+Month12+Yrs

我正在尝试运行96个回归,并将结果保存为96个不同的对象。更复杂的是,我希望模型中一个协变量的下标也改变96次。我几乎解决了这个问题,但不幸的是我遇到了麻烦。到目前为止的代码是

for(i in 1:96){

  assign(paste("z.out", i,sep=""), lm(rMonExp_EGM~ TE_i + Month2+Month3+Month4+Month5+Month6+Month7+Month8+Month9+
  Month10+Month11+Month12+Yrs_minus_2004 + 
  as.factor(LGA),data=Pokies))

}
这在对象创建方面起作用(例如,我有z.out1-z.out96),但我似乎无法使协变量的下标也发生变化

我有96个变量叫做TE_1,TE_2。。。数据集中的TE_96。因此,TE_上的下标“i”需要更改以对应于我创建的每个对象。也就是说,z.out1应保存此模型的结果:

z.out1 <- lm(rMonExp_EGM~ TE_1 + Month2+Month3+Month4+Month5+Month6+Month7+Month8+Month9+
  Month10+Month11+Month12+Yrs_minus_2004 + as.factor(LGA),data=Pokies)

z.out1我将把结果放在一个列表中,避免使用
for循环
assign
语句

您可以结合使用
重新格式化
更新
来创建公式

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)
然后通过以下方式访问单个模型:

 models$z.out5

或者创建所有模型的摘要

 summaries <- lapply(models, summary)

总结谢谢!这就成功了。假设我想从模型中提取系数,那么使用for循环是否明智?示例-颠簸编号。请参见已编辑解决方案中的示例。对于这种活动,循环将起作用,但惯用的R解决方案是使用
lappy
。您在
models$z.out(i)
中使用
i
是不正确的。尝试
模型[[粘贴('z.out',i,sep='')]
。您将无法使用
$
,但除了编程问题之外,您可能应该重新思考或交叉验证时间序列上的lm,将其作为单独的因素。结果肯定是误导性的,或者完全是错误的。
 models$z.out5
 summaries <- lapply(models, summary)
 # just the coefficients
 coefficients <- lapply(models, coef)

 # the table with coefficient estimates and standard.errors

 coef_tables <- apply(summaries, '[[', 'coefficients')