循环回归并以矩阵形式获取汇总统计量

Looping regression and obtaining summary statistics in matrix form

我正在尝试对 25 个不同的投资组合进行类似的回归,然后找到所有 25 个回归的 R^2。显然我可以通过 运行

单独完成它们
P1<-lm(formula = df[1:24,1] - RiskFree ~ Mkt.RF + SMB + HML, data = df ) 
summary(P1)$r.squared

25次得到所有的r.square真的很费时间(无法想象如果是100或更大)。我想做一个循环,这就是我卡住的地方。这就是我所做的

sequence<-seq(1,25)
P<-cbind(sequence)
for(i in 2:26){
P[i-1]<-lm(formula = df[1:24,i] - RiskFree ~ Mkt.RF + SMB + HML, data = df )
return(summary(P[i-1])$r.squared)

哪个returns错误

Error in summary(P[i - 1])$r.squared : $ operator is invalid for atomic vectors In addition: Warning message: In P[i - 1] <- lm(formula = df[1:24, i] - RiskFree ~ Mkt.RF + SMB + : number of items to replace is not a multiple of replacement length`

我如何得到我的 R^2 然后将它们放在矩阵形式中?

(edit) 这是我正在处理的示例数据

df <- "Year SMALL.LoBM ME1.BM2  ME1.BM3  ME1.BM4 Mkt.RF SMB   HML   RiskFree
       1991   -4.61    22.74     16.42    27.89   37.88 2.59 13.60  23.22   
       1992    8.20    20.59     22.90    25.94   40.05 6.66 15.14  16.04
       1993    1.20    12.41     19.27    21.39   37.59 5.46 17.19  23.40   
       1994   -22.67   -0.56     -3.86    1.34     1.93 -3.38-2.28  0.25    
Data <- read.table(text=df, header = TRUE)

你不需要循环。而是使用 lm 接受多个响应变量:

fits <- summary(lm(cbind(mpg, hp) ~ wt, data = mtcars))
#or summary(lm(as.matrix(mtcars[, c(1, 4)]) ~ wt, data = mtcars))
sapply(fits, `[[`, "r.squared")
#Response mpg  Response hp 
#   0.7528328    0.4339488 

这样不仅更优雅,而且更高效。