I have a time series and I try to regress the dependent variables with a lagged regressor. I know that I can do it for a lag of one observation with the following formula:
library(dyn)
set.seed(123)
y <- numeric(100)
y[1] <- 2
for (i in 2:100) {
u <- rnorm(1, mean = 0, sd = 1)
y[i] <- 1 + 0.5 * y[i-1] + u
}
z <- zoo(y)
model <- dyn$lm(z ~ lag(z, -1))
Is there a possibility for aa function which creates 12 regression models with the lagged Regressor from 1 to 12 Observations or do I need to make 12 separate Regressions to get the solutions of the OLS Regression?
Below I show iteration with a for-loop and with purrr::map
.
# OP's code
library(dyn)
#> Loading required package: zoo
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#> as.Date, as.Date.numeric
set.seed(123)
y <- numeric(100)
y[1] <- 2
for (i in 2:100) {
u <- rnorm(1, mean = 0, sd = 1)
y[i] <- 1 + 0.5 * y[i-1] + u
}
z <- zoo(y)
# for-loop version
x <- list()
for(i in 1:12){
x[[i]] <- dyn$lm(z ~ lag(z, -i))
}
x[[9]]
#>
#> Call:
#> lm(formula = dyn(z ~ lag(z, -i)))
#>
#> Coefficients:
#> (Intercept) lag(z, -i)
#> 2.3920 -0.1101
# purrr-based version
library(purrr)
x <- map(1:12, ~ dyn$lm(z ~ lag(z, -.x)))
x[[9]]
#>
#> Call:
#> lm(formula = dyn(z ~ lag(z, -.x)))
#>
#> Coefficients:
#> (Intercept) lag(z, -.x)
#> 2.3920 -0.1101
Created on 2021-07-28 by the reprex package (v2.0.0)
An alternative without purrr
:
x <- lapply(1:12, function(x) dyn$lm(z ~ lag(z, - x)))
x_2[[9]]
#>
#> Call:
#> lm(formula = dyn(z ~ lag(z, -x)))
#>
#> Coefficients:
#> (Intercept) lag(z, -x)
#> 2.3920 -0.1101
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.