# st: RE: Calulate first differences (of sorts)

 From Howard Lempel <[email protected]> To "[email protected]" <[email protected]> Subject st: RE: Calulate first differences (of sorts) Date Fri, 26 Jun 2009 16:33:03 -0400

```xtset subject year
gen diff = D.measure

Hope this helps.
Howie

-----Original Message-----
From: [email protected] [mailto:[email protected]] On Behalf Of Michael Crain
Sent: Friday, June 26, 2009 4:24 PM
To: Statalist
Subject: st: Calulate first differences (of sorts)

I am trying to figure out how to get Stata to calculate the difference between values of a variable based on two observations but only when the subjects are the same. (Sort of a first differencing but with multiple subjects in the data set.)

Using the data set below, I have a fifth variable ('Diff') that is the difference between the values of 'Measure' for the same subject over the previous year. I want to have Stata calculate the difference between 109 & 105 (=4), 119 & 109 (=10) for Subject 1; and the difference between  105 & 90, 97 & 105 for Subject 2. Furthermore, since there is no value for Subject 1 prior to 2001 and prior to 2007 for Subject 2, there is no difference in the values of Measure over a previous year for those two subjects.

Obs Subject Year Measure Diff (Calc. result)
1      1    2001   105            n/a
2      1    2002   109    ?        4
3      1    2003   119    ?       10
4      2    2007    90            n/a
5      2    2008   105    ?       15
6      2    2009    97    ?       -8

_________________________________________________________________
Insert movie times and more without leaving Hotmail(r).
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```