Another solution in the same spirit:
sort id , stable
by id : gen var1 = sum(title != title[_n-1])
Every time that -title- changes, the identifier is incremented by 1.
This works for the first observation in each panel too, as title[1]
differs from title[0] which is taken to be missing.
For much more detail on this approach, see
SJ-7-2 dm0029 . . . . . . . . . . . . . . Speaking Stata: Identifying
spells
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N.
J. Cox
Q2/07 SJ 7(2):249--265 (no
commands)
shows how to handle spells with complete control over
spell specification
Nick
[email protected]
Maarten L. Buis
bys id title : gen byte notfirst = !(_n==1)
bys notfirst id (title): gen tid = _n if notfirst == 0
bys id title (notfirst): gen id2 = sum(tid)
*-------------------- end example ----------------------
(For more on how to use examples I sent to the Statalist, see
http://home.fsw.vu.nl/m.buis/stata/exampleFAQ.html )
Mike Kim
> I would like to create 'var1' in the following table based on id and
> title.
<snip>
> id title var1 var2
> 1 A 1 1
> 1 A 1 2
> 1 B 2 1
> 1 B 2 2
> 1 B 2 3
> 2 C 1 1
> 2 C 1 2
> 2 C 1 3
> 2 D 2 1
> 2 D 2 2
> 3 E 1 1
*----------------- begin example -------------
drop _all
input id str1 title var1 var2
1 A 1 1
1 A 1 2
1 B 2 1
1 B 2 2
1 B 2 3
2 C 1 1
2 C 1 2
2 C 1 3
2 D 2 1
2 D 2 2
3 E 1 1
end
*
* 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/