[R-sig-ME] Solution to fitting -lme4- models with lagged variables

Ben Bolker bbolker at gmail.com
Sun Apr 14 18:10:54 CEST 2013


Clive Nicholas <clivelists at ...> writes:

[snip]
 
> > library(lme4)
> >
> dd=transform(Dyestuff,lagY1=c(NA,head(Yield,-1)),
>                       lagY2=c(rep(NA,2),head(Yield,-2)),
>                         lagY3=c(rep(NA,3),head(Yield,-3)))

  The stuff below is a little bit redundant: if you use

(fit=lmer(Yield~1+lagY1+lagY2+lagY3+(1|Batch),data=dd,REML=T))

then you don't need the other definitions of the lag variables.

  Even more compactly you could define a function:

mylag <- function(x,lag) {
  c(rep(NA,lag),head(x,-lag))
}

dd=transform(Dyestuff,lagY1=mylag(Yield,1),
                      lagY2=mylag(Yield,2),
                      lagY3=mylag(Yield,3))

It's (IMO) a bit of a pity that the built-in lag() function
only works with the (fairly limited) built-in time-series
functionality in R ...



More information about the R-sig-mixed-models mailing list