Here are a few ways:
1) dyn
library(dyn)
Lag <- function(x, k = 1) lag(x, -k)
dyn$lm(X1 ~ Lag(X1) + Lag(X2) - 1, as.zoo(GDP))
giving:
Call:
lm(formula = dyn(X1 ~ Lag(X1) + Lag(X2) - 1), data = as.zoo(GDP))
Coefficients:
Lag(X1) Lag(X2)
-0.1876 0.0772
Note that this would have worked too but defining Lag
as we did above makes it look a bit prettier.
dyn$lm(X1 ~ lag(X1, -1) + lag(X2, -1) - 1, as.zoo(GDP))
2) vars
library(vars)
VAR(GDP, type = "none")
giving:
VAR Estimation Results:
=======================
Estimated coefficients for equation X1:
=======================================
Call:
X1 = X1.l1 + X2.l1
X1.l1 X2.l1
-0.18755204 0.07719922
Estimated coefficients for equation X2:
=======================================
Call:
X2 = X1.l1 + X2.l1
X1.l1 X2.l1
0.4433822 0.2558610
or if we just want to see the first equation:
VAR(GDP, type = "none")[[1]]$X1
giving:
Call:
lm(formula = y ~ -1 + ., data = datamat)
Coefficients:
X1.l1 X2.l1
-0.1876 0.0772
3) No packages
n <- nrow(GDP)
lm(X1[-1] ~ X1[-n] + X2[-n] - 1, GDP)
giving:
Call:
lm(formula = X1[-1] ~ X1[-n] + X2[-n] - 1, data = GDP)
Coefficients:
X1[-n] X2[-n]
-0.1876 0.0772
Note We used the following for GDP in the above examples.
GDP <-
structure(list(X1 = c(-0.480007101227991, -0.710506834821923,
-1.4008090378277, 0.234161619712456, 0.0798157911638669, -0.835197270889505,
0.598254213927639, -1.14352681562672, 1.03688327045929, 0.660297071029499,
-0.351328818974587, 0.790545641075689, -0.792678099784052, -0.357614703160382,
0.314291502993829, -0.431642261560374, 0.316918597548564, 0.5209261331865,
1.0013650951443, 1.05596920913398, -0.753506630185664, -1.4890660967781,
1.43183749932514, -0.423639570640277, 0.637317561276307), X2 = c(0.474962739361749,
-2.39846608215569, -0.98006715899912, -0.0271182048898923, 0.0296705736957689,
-1.24925308595335, -0.893230759394588, 0.241972221010069, -0.431946104440377,
-0.638101222832251, 0.844712933353179, 0.883298568281938, 0.996083349802754,
1.89504374477663, -0.148165464503539, 1.15286878557205, -0.425104835813157,
-1.38572745123415, 1.52226162248381, 1.55272897266444, 1.35700497284096,
0.389532599186254, 0.256357476163037, 1.29116051537444, -0.440232029770923
)), .Names = c("X1", "X2"), row.names = c(NA, -25L), class = "data.frame")