I want to reproduce a randomization the same way each time. Normally I would do this through #set seed and get the same results. But when I used the code below I don't always get the same randomization. Any suggestions on how to randomize within bysort and maintain the same groups or an alternative. See code below.
*randomize to treatment clusters of 20*
set seed 123456
bysort cluster: gen rand = runiform()
sort rand
bysort cluster: gen n = _n //each cluster has 20 observations
// Treatment variable with three levels (5 in each treatment arm and 10 in the control arm)
generate grp = .
replace grp = 1 if n<=5
replace grp = 2 if n>5 & n<=10
replace grp = 3 if n>10
*randomize to treatment clusters of 20*
set seed 123456
bysort cluster: gen rand = runiform()
sort rand
bysort cluster: gen n = _n //each cluster has 20 observations
// Treatment variable with three levels (5 in each treatment arm and 10 in the control arm)
generate grp = .
replace grp = 1 if n<=5
replace grp = 2 if n>5 & n<=10
replace grp = 3 if n>10
Comment