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

 From Philipp Rehm To statalist@hsphsun2.harvard.edu Subject Re: st: Calulate first differences (of sorts) Date Fri, 26 Jun 2009 22:33:20 +0200

```.
Michael,

clear
input Obs Subject Year Measure Diff
1      1    2001   105	.
2      1    2002   109	4
3      1    2003   119	10
4      2    2007    90	.
5      2    2008   105	15
6      2    2009    97	-8
end

tsset Subject Year, yearly
gen difference=d1.Measure

HTH,
Philipp

Michael Crain wrote:
```
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

_________________________________________________________________
```
```*
*   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/
```