[R] How to use "lag"?
Gabor Grothendieck
ggrothendieck at myway.com
Sat Mar 5 18:21:17 CET 2005
Spencer Graves <spencer.graves <at> pdf.com> writes:
:
: Is it possible to fit a lagged regression, "y[t]=b0+b1*x[t-1]+e",
: using the function "lag"? If so, how? If not, of what use is the
: function "lag"? I get the same answer from y~x as y~lag(x), whether
: using lm or arima. I found it using y~c(NA, x[-length(x)])). Consider
: the following:
:
: > set.seed(1)
: > x <- rep(c(rep(0, 4), 9), len=9)
: > y <- (rep(c(rep(0, 5), 9), len=9)+rnorm(9)) # y[t] = x[t-1]+e
: >
: > lm(y~x)
: (Intercept) x
: 1.2872 -0.1064
: > lm(y~lag(x))
: (Intercept) lag(x)
: 1.2872 -0.1064
: > arima(y, xreg=x)
: intercept x
: 1.2872 -0.1064
: s.e. 0.9009 0.3003
: sigma^2 estimated as 6.492: log likelihood = -21.19, aic = 48.38
: > arima(y, xreg=lag(x))
: intercept lag(x)
: 1.2872 -0.1064
: s.e. 0.9009 0.3003
: > arima(y, xreg=c(NA, x[-9]))
: intercept c(NA, x[-9])
: 0.4392 0.8600
: s.e. 0.2372 0.0745
: sigma^2 estimated as 0.3937: log likelihood = -7.62, aic = 21.25
: > arima(ts(y), xreg=lag(ts(x)))
: arima(x = ts(y), xreg = lag(ts(x)))
: intercept lag(ts(x))
: 1.2872 -0.1064
: s.e. 0.9009 0.3003
: sigma^2 estimated as 6.492: log likelihood = -21.19, aic = 48.38
:
Here is some sample code:
R> # following 3 lines are from your post
R> set.seed(1)
R> x <- rep(c(rep(0, 4), 9), len=9)
R> y <- (rep(c(rep(0, 5), 9), len=9)+rnorm(9)) # y[t] = x[t-1]+e
R>
R> # here are some examples using ts class - first one uses no lag
R> lm(y ~ x, cbind(y = ts(y), x = ts(x)))
Call:
lm(formula = y ~ x, data = cbind(y = ts(y), x = ts(x)))
Coefficients:
(Intercept) x
1.2872 -0.1064
R> # now lets redo it with a lag.
R> lm(y ~ lagx, cbind(y = ts(y), lagx = lag(ts(x), -1)) )
Call:
lm(formula = y ~ lagx, data = cbind(y = ts(y), lagx = lag(ts(x), -1)))
Coefficients:
(Intercept) lagx
0.4392 0.8600
R> # here is arima without a lag
R> b <- cbind(ts(y), ts(x))
R> arima(b[,1], order = c(1,1,1), xreg = b[,2])
Call:
arima(x = b[, 1], order = c(1, 1, 1), xreg = b[, 2])
Coefficients:
ar1 ma1 b[, 2]
0.3906 -1.0000 -0.3803
s.e. 0.4890 0.4119 0.3753
sigma^2 estimated as 7.565: log likelihood = -20.2, aic = 48.4
R> # and now we redo arima with a lag
R> bb <- cbind(ts(y), lag(ts(x),-1))
R> arima(bb[,1], order = c(1,1,1), xreg = bb[,2])
Call:
arima(x = bb[, 1], order = c(1, 1, 1), xreg = bb[, 2])
Coefficients:
ar1 ma1 bb[, 2]
-0.2991 -0.8252 0.8537
s.e. 0.4516 1.0009 0.0838
sigma^2 estimated as 0.444: log likelihood = -7.9, aic = 23.8
R> # you can alternately use the I notation with lm and ts objects
R> # if you load zoo first
R> library(zoo)
R> yt <- ts(y); xt <- ts(x)
R> lm(I(yt ~ xt))
Call:
lm(formula = I(yt ~ xt))
Coefficients:
(Intercept) xt
1.2872 -0.1064
R> lm(I(yt ~ lag(xt, -1)))
Call:
lm(formula = I(yt ~ lag(xt, -1)))
Coefficients:
(Intercept) lag(xt, -1)
0.4392 0.8600
More information about the R-help
mailing list