执行与不同列的多个滚动回归(自变量)

问题描述 投票:0回答:2

我怎样才能让多个滚动回归蒙山Y1的依赖性和Y2,Y3等作为单独的回归自变量:

见下面例子:

library(xts)

df=data.frame(y1=rnorm(300),y2=rnorm(300),y3=rnorm(300),y4=rnorm(300),y5=rnorm(300),y6=rnorm(300))
data <- xts(df, Sys.Date()-300:1)

下面我做Y1超过Y2滚动相关

rollingb <- rollapply(zoo(data),
                          width=20,
                          FUN = function(Z)
                          {
                            t = lm(formula=y1~ y2, data = as.data.frame(Z), na.rm=T);
                            return(t$coef)
                          },
                          by.column=FALSE, align="right")

结果看起来不错

plot(rollingb)

但是现在我想测试Y1〜Y3,Y1〜Y4,等等(我有总共120列的数据集)

以下后走得很近,但我无法重现的编码:

https://stackoverflow.com/questions/39438484/r-how-to-do-rolling-regressions-for-multiple-return-data-at-once-with-the-depe

如何调整rollingb来完成这项工作?

通过@Yannis Vassiliadis所提供的解决方案有效,但是跟进的问题上升如何不公开所有的系数(贝塔)很好地成矩阵/ data.frame与相应的日期(如XTS)?

r regression multiple-columns xts rolling-computation
2个回答
1
投票

这个怎么样?

roll_lm <- lapply(2:ncol(data), function(x) rollapply(zoo(data[, c(1, x)]),
                          width=20,
                          FUN = function(Z)
                          { Z = as.data.frame(Z);
                            t = lm(formula=Z[, 1]~Z[, 2]);
                            return(t$coef)
                          },
                          by.column=FALSE, align="right"))

输出与ncol(data) - 1元件,其中该元件ith是从y1的上yi滚动回归的结果的列表。

此外,您还可以添加:

names(roll_lm) <- paste0("y1~y",2:6) 
roll_lm2 <- plyr::rbind.fill.matrix(roll_lm) 
roll_lm3 <- cbind(roll_lm2, rep(names(roll_lm), each = 281)) # just to keep track of the names

0
投票

您可以从map使用purrr打造沿y1 ~ y2y1 ~ y3的线公式的列表。然后在lm使用这些公式。

# these are the packages we are using
library(purrr)
library(useful)
library(coefplot)

# here's your data
df=data.frame(y1=rnorm(300),y2=rnorm(300),y3=rnorm(300),y4=rnorm(300),y5=rnorm(300),y6=rnorm(300))

# keep track of the response variable
response <- 'y1'
# we'll assume all the other variables are predictors
predictors <- setdiff(names(df), response)

# fit a bunch of models
models <- predictors %>% 
    # for each predictor build a formula like y1 ~ y2
    map(~build.formula(response, .x)) %>% 
    # for each of those fit a model
    map(lm, data=df)

# plot them for good measure
multiplot(models)
© www.soinside.com 2019 - 2024. All rights reserved.