如何使用R中的扩展窗口编写线性回归(无包)

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

您如何在不使用包的情况下使用R中的扩展窗口设置线性回归?

设置for循环的最佳方法是什么,以便首先使用30天的数据进行回归,然后使用31天,然后使用32天,依此类推?

r for-loop linear-regression quantitative-finance
1个回答
0
投票

如果您只想举一个如何设置扩展窗口的示例,这里就是一个。它从lapply循环(start)到向量x的长度,回归变量将线性模型拟合到第一个i数据点。

start <- 30
res <- lapply(start:n, function(i){
  k <- seq.int(i)
  fit <- lm(y[k] ~ x[k])
  c(days = i, coef(fit))
})
res <- do.call(rbind, res)

op <- par(mfrow = c(1, 2))
plot(res[,1], res[,2], xlab = "window size", ylab = "Intercept", pch = 16)
plot(res[,1], res[,3], xlab = "window size", ylab = "beta", pch = 16)
par(op)

数据创建代码。

set.seed(1234)

n <- 100
x <- jitter(seq.int(n))
y <- x + rnorm(n)
© www.soinside.com 2019 - 2024. All rights reserved.