【问题标题】:Linear Regression Analysis - rolling across rows线性回归分析 - 跨行滚动
【发布时间】:2016-09-21 15:07:49
【问题描述】:

我需要关于如何获得结果的建议 我的回归分析到一个对象。

我不想逐行执行回归分析 有 20 天的窗口期。 对象 Slope 应将每天回归分析的结果(斜率)保存在窗口中。

    #Loading Library 
    require(quantmod)
    #Initiation of Example
    mc_result  <- matrix(sample(c(1:200)), ncol = 200, nrow =1)
    mc_result1 <- matrix(sample(c(1:200)), ncol =200, nrow =1)
    mc_result <- rbind(mc_result, mc_result1)
    a <- c(1:200)          


    Slope <- matrix(ncol=2, nrow=181)

注意这个循环不起作用。 循环应该逐行应用 Rollapply 并将每天的结果保存在对象 Slope 中。

但是,结果应该是这样的,但斜率值会发生变化。目前斜率值是稳定的,我不知道为什么。

    for (i in 1:2) { 

    Slope[,i] <- rollapply(data =mc_result[i,], width=20, 
                          FUN = function(z)
                            summary(lm(mc_result[i,]  ~ a, data =  as.data.frame(z)))$coefficients[2], by.column = FALSE) 
    }

【问题讨论】:

    标签: r quantmod


    【解决方案1】:

    我认为您想要的是以下内容(在您的代码中,mc_result[i,] 或 a 都没有滚动数据中的索引,这就是线性回归系数没有改变的原因,因为您正在接受相同的训练数据集,只有z在变化,您需要将代码更改为以下内容):

    #Loading Library 
    require(quantmod)
    #Initiation of Example
    mc_result  <- matrix(sample(c(1:200)), ncol = 200, nrow =1)
    mc_result1 <- matrix(sample(c(1:200)), ncol =200, nrow =1)
    mc_result <- rbind(mc_result, mc_result1)
    a <- c(1:200)          
    Slope <- matrix(ncol=2, nrow=181)
    
    for (i in 1:2) { 
    
      Slope[,i] <- rollapply(data = 1:200, width=20, 
                             FUN = function(z) {
                               summary(lm(mc_result[i,z]  ~ a[z]))$coefficients[2]
                             }, by.column = FALSE) 
    }
    
    head(Slope)
              [,1]      [,2]
    [1,] 1.3909774 2.0278195
    [2,] 1.0315789 2.8421053
    [3,] 1.5082707 2.8571429
    [4,] 0.0481203 1.6917293
    [5,] 0.2969925 0.2060150
    [6,] 1.3526316 0.6842105
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 2022-01-16
      • 2015-04-03
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多