# Re: st: How Can I Create the Variable x?

 From John Fulton <[email protected]> To [email protected] Subject Re: st: How Can I Create the Variable x? Date Sun, 28 Jan 2007 21:39:06 -0500

Raphael,
This code works as far as your example data goes:

bysort id: gen x=_n if _n==1
/* set first value of x for each id */
replace x=x[_n-1] if bsid==bsid[_n-1] /* keep x the same if current bsid=previous bsid */
replace x=x[_n-1]+1 if bsid!=bsid[_n-1] & id==id[_n-1]
/* increment x if cur.bsid!=prev. bsid and id is the same */

I think it will work on any dataset but obviously I haven't tested it.

Raphael Fraser wrote:

```I need help in creating the var x.

id bsid  x
1  22    1
1  22    1
1  52    2
1  87    3
2  43    1
2  43    1
2  11    2
3  28    1
4  33    1

I have tried,
bysort id bsid: gen x = _n
bysort id (bsid): gen x = _n

Regards,
Raphael
*
*   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/
```
```*
*   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/
```