|Title||Stata 5: Creating lagged variables|
|Author||James Hardin, StataCorp|
Create lag (or lead) variables using subscripts.
. gen lag1 = x[_n-1] . gen lag2 = x[_n-2] . gen lead1 = x[_n+1]
You can create lag (or lead) variables for different subgroups using the by prefix. For example,
. sort state year . by state: gen lag1 = x[_n-1]
If there are gaps in your records and you only want to lag successive years, you can specify
. sort state year . by state: gen lag1 = x[_n-1] if year==year[_n-1]+1
See [D] egen for details on creating variables of moving averages.