我需要一个建议,我如何得到我的回归分析结果到一个对象。
我不想用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)
}发布于 2016-09-21 16:53:57
我认为您想要的是以下内容(在您的代码中没有mc_resulti,或者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.6842105https://stackoverflow.com/questions/39620272
复制相似问题