5

96 回の回帰を実行し、結果を 96 個の異なるオブジェクトとして保存しようとしています。複雑なことに、モデルの共変量の 1 つの下付き文字も 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 があります) が、共変量の添え字も変更できないようです。

データセットには、TE_1、TE_2 ... TE_96 と呼ばれる 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.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)

うまくいけば、これは理にかなっています。ヒント/アドバイスに感謝します。

4

1 に答える 1

7

結果をリストに入れ、for loopandassignステートメントを避けます

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)

リストには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 = '' )  

次に、単一のモデルにアクセスします

 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')
于 2012-11-09T05:04:48.920 に答える