0

如何在单独的回归中将 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 提供的解决方案有效,但是后续问题提出了如何将所有系数(beta)很好地取消列出到具有相应日期的矩阵/data.frame 中(如在 xts 中)?

4

2 回答 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元素是 on 的滚动回归的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
于 2018-04-30T17:36:46.630 回答
0

您可以使用mapfrom沿和purrr的行构建公式列表。然后在 中使用这些公式中的每一个。y1 ~ y2y1 ~ y3lm

# 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)
于 2018-04-30T17:38:40.090 回答