title: general lag in time series panel data
body: <p>I have a dataset akin to this</p>
  
  <pre><code>User    Date        Value
  A       2012-01-01  4
  A       2012-01-02  5   
  A       2012-01-03  6
  A       2012-01-04  7
  B       2012-01-01  2
  B       2012-01-02  3   
  B       2012-01-03  4
  B       2012-01-04  5
  </code></pre>
  
  <p>I want to create a lag of <code>Value</code>, respecting <code>User</code>. </p>
  
  <pre><code>User    Date        Value   Value.lag
  A       2012-01-01  4       NA
  A       2012-01-02  5       4
  A       2012-01-03  6       5
  A       2012-01-04  7       6
  B       2012-01-01  2       NA
  B       2012-01-02  3       2   
  B       2012-01-03  4       3
  B       2012-01-04  5       4
  </code></pre>
  
  <p>I've done it very inefficiently in a loop </p>
  
  <pre><code>df$value.lag1&lt;-NA
  levs&lt;-levels(as.factor(df$User))
  levs
    for (i in 1:length(levs)) {
      temper&lt;- subset(df,User==as.numeric(levs[i]))
      temper&lt;- rbind(NA,temper[-nrow(temper),])  
  df$value.lag1[df$User==as.numeric(as.character(levs[i]))]&lt;- temper
        }
  </code></pre>
  
  <p>But this is very slow. I've looked at using <code>by</code> and <code>tapply</code>, but not figured out how to make them work. </p>
  
  <p>I don't think XTS or TS will work because of the User element. </p>
  
  <p>Any suggestions? </p>