Michael Blasnik's solution seems by far the 
neatest proposed: 
bysort id (bsid): gen x=sum(bsid!=bsid[_n-1])
Nick 
[email protected] 
Jason Ferris
 
> clear
> input id bsid 
> 1  22 
> 1  22 
> 1  52 
> 1  87 
> 2  43 
> 2  43 
> 2  11 
> 3  28 
> 4  33 
> end 
> bysort id : egen x=seq() if bsid~=bsid[_n-1] /* sequence starts the
> ordering */
> replace x=x[_n-1] if x==. /* fills in the missing gaps */
*
*   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/