如何在 R 中用扩展 window 编写线性回归(无包)

How to write a linear regression with an expanding window in R (no packages)

如何在不使用包的情况下在 R 中设置具有扩展 window 的线性回归?

设置 for 循环以便首先使用 30 天、31 天、32 天等进行回归的最佳方法是什么?

如果您只想了解如何设置展开式 window 的示例,这里有一个。它从 start 循环 (lapply) 到向量 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)