【问题标题】:Loop Regression and Store Intercepts, Slopes, etc循环回归和存储截距、斜率等
【发布时间】:2020-10-16 07:25:48
【问题描述】:

我需要使用循环将每家公司的收益回归到指数收益: 公司回报为:

       AAPL         AXP          BA         CAT        CSCO         CVX          DD         DIS          GE          GS          HD 
 12.3360728 -13.9214932  22.5635983 -27.2829432  24.1013814 -20.3403951   0.4449273  28.1967333  20.3767961   3.9267703  30.2680724 
        IBM        INTC         JNJ         JPM          KO         MCD         MMM         MRK        MSFT         NKE         PFE 
 -7.8815087   8.0829670  -1.3179946  12.5467514   8.2271155  24.7729246   7.6478088  -0.5601629  21.9812572  39.4680023  19.9745312 
         PG         TRV         UNH         UTX           V          VZ         WMT         XOM 
 -6.7330018  16.4542731  27.3932024  -1.2581727  41.5225073  -1.2022588 -23.1585254  -9.7806252 

并且索引返回是:

    ^DJI 
4.910218 

我想:

  1. 打印所有公司 i = 1, ..., 30, 的截距、斜率 (βi) 和特殊标准差 σRi(残差的标准差)的表格

  2. 计算并打印指数回报的方差,

  3. 使用计算的 σ^2M 、 βi 和 σRi 计算所有 i 的协方差矩阵 Qsi 的单索引近似值 注意:Ω 的对角线项是 σ^2Ri,而不是 σRi

基本上,我只需要循环执行不同的回归并以某种方式存储这些信息。有人可以帮忙吗?

【问题讨论】:

    标签: r loops regression linear-regression linear-algebra


    【解决方案1】:

    这是一个简单的示例,您可以使用它来开发自己的代码。此代码循环遍历mtcars 数据集的变量,并使用mpg 作为目标变量来估计线性模型:

    ref_variable <- "mpg"
    target_vars <- c("hp","wt","qsec")
    
    # container results
    res <- data.frame(matrix(NA,0,4), stringsAsFactors = FALSE)
    names(res) <- c("variable", "intercept", "slope", "std_dev_resid")
    
    for (var in target_vars){
      linear_model <- lm(as.formula(paste0(ref_variable,"~",var)), data = mtcars)
      res <- rbind(res, data.frame(variable=var,
                          intercept=linear_model$coefficients[[1]], # intercept
                          slope=linear_model$coefficients[[2]], # slope
                          std_dev_resid=sd(resid(linear_model)) # std dev of residuals
                          ))
    }
    

    输出

      variable intercept       slope std_dev_resid
    1       hp 30.098861 -0.06822828     0.5262956
    2       wt 37.285126 -5.34447157     0.6674783
    3     qsec -5.114038  1.41212484     0.3654127
    

    【讨论】:

    • 非常感谢您,但我不得不问这是否也适用于时间序列对象之间的回归?我愚蠢地将一个数字与另一个数字回归,但我的意思是让一个时间序列与另一个时间序列回归。
    • @eruiz 当然,在我的示例中,我使用了数据框。它的列可以被认为是时间序列。在 Rstudio 中输入“mtcars”以检查数据集。
    • @eruiz 修正了一个错字。试试编辑后的代码,它现在可以工作了
    • 效果非常好!我有一个关于残差标准差的问题。在我的作业中,它说“特殊标准偏差 σRi(残差的标准偏差)”。我的理解是 lm() 计算 sigma 为 the square root of the estimated variance of the random error σ^2 = 1/(n-p) Sum(w[i] R[i]^2), where R[i] is the i-th residual, residuals[I]. 你能解释一下为什么你使用你所做的公式吗?
    • @eruiz 我实际上不知道为什么我把 2 放在那里。我猜是另一个错字。我的错,对不起。您需要残差的 std.dev 吗?然后只需使用sd(resid(linear_model))
    猜你喜欢
    • 2014-02-28
    • 2015-09-09
    • 2014-06-18
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2014-02-15
    相关资源
    最近更新 更多