# Re: st: Re: programming advice

 From Phil Schumm <[email protected]> To [email protected] Subject Re: st: Re: programming advice Date Fri, 17 Dec 2004 04:56:14 -0600

```At 10:10 AM +0000 12/17/04, Ed Weil wrote:
```
I often get data of this form where x0 corresponds to the value of x1 when month = 0 for each set within code1. This needs to be subtracted from x1 to get a difference. Due to my lack of programming skills I have to inspect the dataset and manually enter the values of x0 for each set of code1. I was trying to write a do-file using if constructs to achieve this with no success. Could somebody tell me if it is possible to program this and point me in the correct direction. The number of results within each "code1" varies.
list code1 month x1 x0 in 11/25

+---------------------------------+
| code1 month x1 x0 |
|---------------------------------|
11. | 6 0 -1.07 -1.07 |
12. | 6 3 -.632 -1.07 |
13. | 7 0 -.292 -.292 |
14. | 7 3 -.595 -.292 |
15. | 8 0 -.269 -.269 |
|---------------------------------|
16. | 8 3 -.056 -.269 |
17. | 9 0 -1.336 -1.336 |
18. | 9 3 -.83 -1.336 |
19. | 9 9 -.792 -1.336 |
20. | 9 16 -.153 -1.336 |
|---------------------------------|
21. | 10 0 -.64 -.64 |
22. | 10 3 -.615 -.64 |
23. | 10 16 -.559 -.64 |
24. | 11 0 -.8 -.8 |
25. | 11 3 -.35 -.8 |
+---------------------------------+

Ed,

Assuming that code1, month, and x1 are as above (and x0 doesn't yet exist), the following will do what you want:

bys code1 (month): gen x0 = x1[1] if month[1]==0

The key thing to recognize here is that by prefixing the command with -by-, the construct x1[1] refers to the first observation within the by-group (in this case, within code1). The addition of (month) makes certain that within each value of code1, the observations are in ascending order of month (so that the first one corresponds to month==0). For more information, see [R] by.

If I were doing this, I'd probably want to verify (before I did it) that within each value of code1 there was one and only one observation for which month==0. One way to do this is with the following:

bys code1 (month): ass month[1]==0 & month[2]!=0

which will throw an error if this condition is not met.

-- Phil
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/