countstatagroupmultiple-occurrence

How to create a variable that counts the number of occurrences of another variable (1 for first occurrence, 2 for second etc)


I have this data:

#id time 
#1  1
#1  2
#2  1
#2  2
#2  1
#2  2
#3  1
#3  2

And I want to create a variable that looks at the id and time combination and puts a 1 the first time it sees it and 2 the second time it sees it. So this occurrence variable:

#id time occurrence
#1  1    1
#1  2    1
#2  1    1
#2  2    1
#2  1    2
#2  2    2
#3  1    1
#3  2    1

How would I do that?


Solution

  • //create original sort order, otherwise occurrence order might differ
    gen original_order = _n
    
    //create occurrence variable
    bysort time id (original_order): gen occurrence = _n
    
    //sort on original order
    sort original_order
    drop original_order