[R] The opposite of "lag"

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jul 21 16:50:57 CEST 2010


On Wed, Jul 21, 2010 at 10:14 AM, Dimitri Liakhovitski
<dimitri.liakhovitski at gmail.com> wrote:
> Hello!
>
> I have a data frame A (below) with a grouping factor (group). I take
> my DV and create the new, lagged DV by applying the function lag.it
> (below). It works fine.
>
> A <- data.frame(year=rep(c(1980:1984),3), group=
> factor(sort(rep(1:3,5))), DV=c(rnorm(15)))
> lag.it <- function(x) {
>  DV <- ts(x$DV, start = x$year[1])
>  idx <- seq(length = length(DV))
>  DVs <- cbind(DV, lag(DV, -1))[idx,]
>  out<-cbind(x, DVs[,2])  # wages[,2]
>   names(out)[length(out)]<-"DV.lag"
>   return(out)
> }
> A
> A.lagged <- do.call("rbind", by(A, A$group, lag.it))
> A.lagged
>
>
> Now, I am trying to create the oppostive of lag for DV (should I call
> it "lead"?)
> I tried exactly the same as above, but with a different number under
> lag function (below), but it's not working. I am clearly doing
> something wrong. Any advice?
> Thanks a lot!
>
>
> lead.it <- function(x) {
>  DV <- ts(x$DV, start = x$year[1])
>  idx <- seq(length = length(DV))
>  DVs <- cbind(DV, lag(DV, 2))[idx,]
>  out<-cbind(x, DVs[,2])
>   names(out)[length(out)]<-"DV.lead"
>   return(out)
> }
> A
> A.lead <- do.call("rbind", by(A, A$group, lead.it))
> A.lead
>

Try this:

library(zoo)
z <- read.zoo(A, index = 1, split = "group", frequency = 1)
lag(z, c(-1, 0, 1))



More information about the R-help mailing list