title: Create lead and lag variables in R
body: <p>I have to create lead and lag variables like below in R</p>
  
  <p>Suppose i have a dataframe which has details about a customer's visit to any store...</p>
  
  <pre><code>CustomerID  Dateofvisit
  1   1/2/2013
  1   1/3/2013
  1   1/7/2013
  2   1/9/2013
  2   1/14/2013
  2   2/14/2013
  3   1/4/2013
  3   1/5/2013
  </code></pre>
  
  <p>As we can see, there are 3 customers with different visit dates.. When i apply a lag function on the above...(i created my own function,)..it becomes like below:</p>
  
  <pre><code>CustomerID  Dateofvisit Laggeddate
  1   1/2/2013    -
  1   1/3/2013         1/2/2013
  1   1/7/2013         1/3/2013
  2   1/9/2013         1/7/2013
  2   1/14/2013        1/9/2013
  2   2/14/2013        1/14/2013
  3   1/4/2013         2/14/2013
  3   1/5/2013         1/4/2013
  </code></pre>
  
  <p>But, i want to lag by customer as well. So for the 4th row, the lagged date should be nothing..similarly for the 3rd cstomer, first row/entry should be notihng and on last row, i should see 1/4/2013.. How do i do this?</p>
  
  <p>The following is code i use for lag/lead</p>
  
  <pre><code>shift&lt;-function(x,shift_by){ 
      stopifnot(is.numeric(shift_by)) 
      stopifnot(is.numeric(x)) 
  
      if (length(shift_by)&gt;1) 
          return(sapply(shift_by,shift, x=x)) 
  
      out&lt;-NULL
      abs_shift_by=abs(shift_by) 
      if (shift_by &gt; 0 ) 
          out&lt;-c(tail(x,-abs_shift_by),rep(NA,abs_shift_by)) 
      else if (shift_by &lt; 0 ) 
          out&lt;-c(rep(NA,abs_shift_by), head(x,-abs_shift_by)) 
      else 
          out&lt;-x 
      out 
  }
  </code></pre>
  
  <p>and how i lead/lag them:</p>
  
  <pre><code>#generate lead by 1 variable 
  test$df_lead2&lt;-shift(test$x,1) 
  #generate lag by 1 variable 
  test$df_lag2&lt;-shift(test$x,-1) 
  </code></pre>
  
  <p>My desired output is:</p>
  
  <pre><code>CustomerID  Dateofvisit Laggeddate
  1   1/2/2013    -
  1   1/3/2013         1/2/2013
  1   1/7/2013         1/3/2013
  2   1/9/2013         -
  2   1/14/2013        1/9/2013
  2   2/14/2013        1/14/2013
  3   1/4/2013         -
  3   1/5/2013         1/4/2013
  </code></pre>