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

kpe*_*ton 5 loops for-loop regression r

我正在尝试运行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))

}
Run Code Online (Sandbox Code Playgroud)

这适用于对象创建方(例如我有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)
Run Code Online (Sandbox Code Playgroud)

并且z.out96应该是:

z.out96 <- lm(rMonExp_EGM~ TE_96+ Month2+Month3+Month4+Month5+Month6+Month7+Month8+Month9+
  Month10+Month11+Month12+Yrs_minus_2004 + as.factor(LGA),data=Pokies)
Run Code Online (Sandbox Code Playgroud)

希望这是有道理的.我很感激任何提示/建议.

mne*_*nel 7

我会将结果放在一个列表中,并避免使用for loopassign语句

您可以使用的组合 reformulate,并update以创建公式

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)
Run Code Online (Sandbox Code Playgroud)

现在列表中应该有96个元素 models

您可以将它们命名为反映最初计划的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 = '' )  
Run Code Online (Sandbox Code Playgroud)

然后通过访问单个模型

 models$z.out5
Run Code Online (Sandbox Code Playgroud)

等等

或创建所有模型的摘要

 summaries <- lapply(models, summary)
Run Code Online (Sandbox Code Playgroud)

等等....

 # just the coefficients
 coefficients <- lapply(models, coef)

 # the table with coefficient estimates and standard.errors

 coef_tables <- apply(summaries, '[[', 'coefficients')
Run Code Online (Sandbox Code Playgroud)