有没有办法在不折叠数据的情况下在面板中产生滞后?

Is there a way to generate lags in a panel without collapsing the data?

我有一个看起来像这样的数据集

State     Year      Policy      other_variables
 a        2000        0               18
 a        2000        0               19
                  .
                  .
                  .
 a        2001        1               86
 a        2001        1               23

poicy 值在每个州和年份内是恒定的。但它会因不同的州和不同的年份而变化。 other_variables 每次观察都不同。

我想为每个州生成政策值的滞后。但是,我不能使用 xtset state year 然后使用 L 运算符。每个州年份组合中都有重复的值。我知道折叠数据集、生成滞后变量然后合并回数据集是可行的。我的问题是有没有简单的方法来做这个操作?

这可能有帮助:

clear 
input str1 State     Year      Policy    
 a        2000        0               
 a        2000        0               
 a        2001        1               
 a        2001        1               
 end 

 bysort State (Year) : gen diff = Policy - Policy[_n-1] if Year == Year[_n-1] + 1 
 by State Year: replace diff = diff[_n-1] if missing(diff) 

 list, sepby(State Year) 

     +------------------------------+
     | State   Year   Policy   diff |
     |------------------------------|
  1. |     a   2000        0      . |
  2. |     a   2000        0      . |
     |------------------------------|
  3. |     a   2001        1      1 |
  4. |     a   2001        1      1 |
     +------------------------------+