[R] A couple of little R things I can't figure out (column percents, regression with lagged variables)
Thomas Lumley
tlumley at u.washington.edu
Tue Feb 12 14:47:28 CET 2002
On 12 Feb 2002, Peter Dalgaard BSA wrote:
> > 2. A student said here's y, a vector representing a time series, and
> > here's x, a vector representing a time series. I want to do a
> > conventional regression of y on the lag of x. In sas you do
> > xlag=lag(x) and then use xlag in a regresson. I just want something
> > simple like lm(y~lag(x)). But in R base there's no lag.
> >
> > So I can get it the old fashioned way:
> > > xx <- c(NA,x)
> > > modl <- lm(y~xx[1:length(y)])
> > > summary(modl)
> >
> > One sidenote is that summary does not include any mention of the fact
> > that 1 observation was lost due to missing value. That seems bad to me.
> >
> > I see the lag function in ts, but when I use it, it doesn't change x,
> > so obviously I don't see the point of that.
> >
> > > z <- lag (x)
> > > z
> > [1] 1 3 1 3 1 3 1 3 4 4
>
> This stuff only works for time series, e.g. cbind(ts(x),lag(ts(x))).
> Notice that even then, lag() works in the opposite direction (for
> historical reasons).
>
You could, however, write a function
mylag<-function(x,d=1) {
n<-length(x)
c(rep(NA,d),x)[1:n]
}
and use lm(y~mylag(x))
-thomas
Thomas Lumley Asst. Professor, Biostatistics
tlumley at u.washington.edu University of Washington, Seattle
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list