mar
mar

Reputation: 13

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

How do you set up a linear regression with an expanding window in R without using packages?

What is the best way to set up a for loop so that the regression is done first with 30 days of data, then 31 days, then 32, etc?

Upvotes: 0

Views: 342

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

If all you want is an example of how to set up an expanding window, here is one. It loops (lapply) from start to the length of vector x, the regressor fitting a linear model to the first i data points.

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)

Data creation code.

set.seed(1234)

n <- 100
x <- jitter(seq.int(n))
y <- x + rnorm(n)

Upvotes: 1

Related Questions