[R] Using time series and lm

Gabor Grothendieck ggrothendieck at myway.com
Sat Feb 19 04:15:36 CET 2005


Matthieu Cornec <matthieu.cornec <at> gmail.com> writes:
> I create a multivariate time series containing NA values. 
> I want to compute a linear regression and obtain a time serie for both
> residuals and fitted values. I have tried the trick ts.intersect,
> without success.
> 
> Could you help me out of this?
> ####
> Example:
> 
> y<-ts(1:10+rnorm(10))
> x<-ts(1:10)
> datats<-cbind(y,lagx=lag(x))

Are you sure that you want lag(x) here?  lag(x) moves the time scale
one unit earlier so this will predict a past y based on a future x.
I think you probably meant lag(x, -1).    (I have continued to use
lag(x) below for consitency with your post.)

> 
> Notice the datats could come directly from an imported file, that is
> why I did not use ts.intersect(y,lagx=lag(x))
> 
> fit<-lm(y~lagx,data=datats,na.action=na.omit)
> 
> but how do I get a time serie of residuals instead of a vector residuals
(fit)?

# Define this function:
plain2ts <- function(x, ts.) ts(x, start = start(ts.), freq = frequency(ts.))

# It can be used like this:
datats.na <- na.omit(datats)
datats.fit <- lm(y ~ lagx, datats.na)
datats.resid <- plain2ts(resid(datats.fit), datats.na)

# Also note that using the zoo package one can directly perform
# lm on ts objects and it will automatically align them provided
# you surround the formula with I(...):

library(zoo)
fit2 <- lm(I(y ~ lag(x))) # y and x are the ts objects in your post

however, you would still have to use the previous method to convert
the residuals back to ts class as that is not currently handled.
For more on zoo:

library(zoo)
vignette("zoo")




More information about the R-help mailing list