[R] How to use "lag"?

Gabor Grothendieck ggrothendieck at myway.com
Sat Mar 5 18:24:53 CET 2005


Dirk Eddelbuettel <edd <at> debian.org> writes:

> 
> Spencer,
> 
> You may want to peruse the list archive for posts that match 'ts' and are
> written by Brian Ripley -- these issues have come up before. 
> 
> The ts class is designed for arima and friends (like Kalman filtering), and
> very useful in that context, but possibly not so much anywhere else.  lag()
> only shifts the _reference dates_ attached to the object. So in a data.frame
> context (as for lm()) .... nothing happens.
> 
> Personally, I use its as my main container for daily or weekly data. There is
> also zoo, which I have meant to examine more closely for a while now.  

Here is the example redone using zoo:

R> # here it is redone using zoo objects
R> 
R> # following 3 lines are from the original 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> library(zoo)
R> 
R> yz <- zoo(y); xz <- zoo(x)
R> lm(I(yz ~ xz))

Call:
lm(formula = I(yz ~ xz))

Coefficients:
(Intercept)           xz  
     1.2872      -0.1064  

R> lm(I(yz ~ lag(xz, -1)))

Call:
lm(formula = I(yz ~ lag(xz, -1)))

Coefficients:
(Intercept)  lag(xz, -1)  
     0.4392       0.8600  

R> 
R> z <- merge(yz, xz)
R> arima(coredata(z[,1]), order = c(1,1,1), xreg = coredata(z[,2]))

Call:
arima(x = coredata(z[, 1]), order = c(1, 1, 1), xreg = coredata(z[, 2]))

Coefficients:
         ar1      ma1  coredata(z[, 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> zz <- merge(yz, lag(xz, -1))
R> arima(coredata(zz[,1]), order = c(1,1,1), xreg = coredata(zz[,2]))

Call:
arima(x = coredata(zz[, 1]), order = c(1, 1, 1), xreg = coredata(zz[, 2]))

Coefficients:
          ar1      ma1  coredata(zz[, 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




More information about the R-help mailing list