问题描述
我正在尝试对 25 个不同的投资组合进行类似的回归,然后找到所有 25 个回归的 R^2.显然我可以通过运行来单独完成它们
I am trying to do a similar regression for 25 different portfolios and then finding the R^2 of all 25 regressions. Obviously i can do them individually by running
P1<-lm(formula = df[1:24,1] - RiskFree ~ Mkt.RF + SMB + HML, data = df )
summary(P1)$r.squared
25 次才能得到所有的 r.square,这真的很耗时(无法想象它是 100 还是更大).我想做一个循环,这就是我卡住的地方.这就是我所做的
25 times to get all the r.square which is really time consuming (can't imagine if it's 100 or greater). I thought of doing a loop and here is where i got stuck. This is what i did
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)
返回错误
总结错误(P[i - 1])$r.squared:$ 运算符对原子向量无效另外: 警告信息:在 P[i - 1]
如何得到我的 R^2,然后将它们以矩阵形式放置?
How do i get my R^2 and then place them in a matrix form?
(编辑)这是我正在处理的示例数据
(edit) this is the sample data that i am working on
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
接受多个响应变量:
You don't need a loop. Instead use that lm
accepts multiple response variables:
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
这不仅更优雅,而且更高效.
This is not only more elegant, but also more efficient.
这篇关于循环回归并以矩阵形式获取汇总统计量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!