What's the opposite function to lag for an R vector/dataframe?

How about the built-in 'lead' function? (from the dplyr package) Doesn't it do exactly the job of Ahmed's function?

cbind(x, lead(y, 1))

If you want to be able to calculate either positive or negative lags in the same function, i suggest a 'shorter' version of his 'shift' function:

shift = function(x, lag) {
  require(dplyr)
  switch(sign(lag)/2+1.5, lead(x, abs(lag)), lag(x, abs(lag)))
}

What it does is creating 2 cases, one with lag the other with lead, and chooses one case depending on the sign of your lag (the +1.5 is a trick to transform a {-1, +1} into a {1, 2} alternative).


There is an easier way of doing this which I have captured fully from this link. What I will do here is explaining what should you do in steps:

First create the following function by running the following code:

shift<-function(x,shift_by){
    stopifnot(is.numeric(shift_by))
    stopifnot(is.numeric(x))

    if (length(shift_by)>1)
        return(sapply(shift_by,shift, x=x))

    out<-NULL
    abs_shift_by=abs(shift_by)
    if (shift_by > 0 )
        out<-c(tail(x,-abs_shift_by),rep(NA,abs_shift_by))
    else if (shift_by < 0 )
        out<-c(rep(NA,abs_shift_by), head(x,-abs_shift_by))
    else
        out<-x
    out
}

This will create a function called shift with two arguments; one is the vector you need to operate its lag/lead and the other is number of lags/leads you need.

Example:

Suppose you have the following vector:

x<-seq(1:10)

x
 [1]  1  2  3  4  5  6  7  8  9 10

if you need x's first order lag

shift(x,-1)
[1] NA  1  2  3  4  5  6  7  8  9 

if you need x's first order lead (negative lag)

shift(x,1)
[1]  2  3  4  5  6  7  8  9 10 NA

The opposite of lag() function is lead()