title: Lag a variable with non unique id x time observations
body: <p>I have a repeated cross section every year. I have a variable, <code>var1</code>, which is the same across all observations in a given year (for instance, the mean of a variable in a given year). I'd like to create a variable, <code>var1_l</code>, that would be the lagged version of <code>var1</code>.</p>
  
  <p>As an example, from the dataset</p>
  
  <pre><code>  id1   year    var1
     3    1990     3.5
     4    1990     3.5
     5    1991       4
     6    1991       4
     7    1991       4
  </code></pre>
  
  <p>I would like to obtain</p>
  
  <pre><code>  id1   year    var1 var1_l
     3    1990     3.5      .
     4    1990     3.5      .
     5    1991       4    3.5
     6    1991       4    3.5
     7    1991       4    3.5
  </code></pre>
  
  <p>A solution would be to use a <code>merge</code> but saving/restoring the dataset takes a lot of time when the dataset is big. For reference, below is my current <code>merge</code> solution:</p>
  
  <pre><code>preserve
  keep year var1
  replace year = year - 1
  bys year: keep if _n == 1
  rename var1 var1_l
  sort year
  tempfile temp
  save `temp'
  restore
  merge m:1 year using `temp', nogen sorted
  </code></pre>
  
  <p>Another option would be to use the matrix returned by <code>tabstat</code>. I'm wondering if there is a more elegant solution (that returns . when there is no observation in year - 1).</p>