1

Given the following variables (id and partner) in Stata, I would like to create a new variable (pid) that is simply the consecutive partner counter within id (as you can see, partner is not consecutive). Here is a MWE:

clear
input   id  partner pid
        1   1       1
        1   1       1
        1   3       2
        1   3       2
        2   2       1
        2   3       2
        2   3       2
        2   3       2
        2   5       3
        2   5       3
end
Bernd Weiss
  • 927
  • 1
  • 14
  • 24

1 Answers1

2
// create example data
clear
input   id  partner
        1   1      
        1   1      
        1   3      
        1   3     
        2   2     
        2   3     
        2   3     
        2   3     
        2   5     
        2   5     
end

// create pid
bysort id partner : gen pid = _n == 1
by id : replace pid = sum(pid)

// admire the result
list, sepby(id)
Maarten Buis
  • 2,684
  • 12
  • 17