[R] The opposite of "lag"

Dimitri Liakhovitski dimitri.liakhovitski at gmail.com
Wed Jul 21 18:12:41 CEST 2010


Never mind- I figured it out:

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

Thank you very much!

On Wed, Jul 21, 2010 at 12:08 PM, Dimitri Liakhovitski
<dimitri.liakhovitski at gmail.com> wrote:
> Thank you, Gabor, but sorry - what is the exact order of those rows again?
> Thank you!
> Dimitri
>
> On Wed, Jul 21, 2010 at 11:59 AM, Gabor Grothendieck
> <ggrothendieck at gmail.com> wrote:
>> On Wed, Jul 21, 2010 at 10:50 AM, Gabor Grothendieck
>> <ggrothendieck at gmail.com> wrote:
>>> 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))
>>>
>>
>> The ### line was missing:
>>
>> library(zoo)
>> z <- read.zoo(A, index = 1, split = "group", frequency = 1)
>> z <- as.zooreg(z) ###
>> lag(z, c(-1, 0, 1))
>>
>
>
>
> --
> Dimitri Liakhovitski
> Ninah Consulting
> www.ninah.com
>



-- 
Dimitri Liakhovitski
Ninah Consulting
www.ninah.com



More information about the R-help mailing list