2016-09-21 131 views
0

我需要一个关于如何将我的回归分析结果 转化为对象的建议。线性回归分析 - 滚动行

我不想执行回归分析行明智和 与20天的窗口。 对象坡度应该将每天回归分析的结果(斜率)保存在窗口中。

#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行明智 并保存在对象斜率每天的结果。

但是,这是结果应该如何,但改变斜率值。目前斜坡价值稳定,我不知道为什么。

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) 
    } 

回答

0

我想你想要的是以下(在你的代码没有mc_result的[我]或者是翻转的数据指标,这就是为什么线性回归系数并没有改变,因为你是在相同的数据集上进行培训,只有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 
+0

完美。现在我知道这是为什么发生了......谢谢! – user6771241