I have a panel dataset that has 18 observations per spgrid_id (months). I want to within 3 blocks randomize. Its easy to do if I collapse, but I figured there has to be a simple way to do this within STATA. The code I wrote below randomizes within block, but I want to assign treatment based on three groups.
How can I created 3 groups within each block that I could then randomize within the block?
* Block 1: ranks 1–10, Block 2: 11–20, Block 3: 21–30
gen block = ceil(rank / 10)
* Set seed for reproducibility
set seed 123456
* One random draw per unit
bysort spgrid_id: gen double rand = runiform() if _n == 1
bysort spgrid_id: replace rand = rand[1]
* Sort within block by random draw
sort block rand spgrid_id
* Sequence within each block (1–10) and month
bysort block spgrid_id (ym): gen month = _n
* Generate treatment indicator based on randomized treatment start times
gen treatment = 0
replace treatment = 1 if (block == 1 & month >= 6)
replace treatment = 1 if (block == 2 & month >= 8)
replace treatment = 1 if (block == 3 & month >= 12)
How can I created 3 groups within each block that I could then randomize within the block?
* Block 1: ranks 1–10, Block 2: 11–20, Block 3: 21–30
gen block = ceil(rank / 10)
* Set seed for reproducibility
set seed 123456
* One random draw per unit
bysort spgrid_id: gen double rand = runiform() if _n == 1
bysort spgrid_id: replace rand = rand[1]
* Sort within block by random draw
sort block rand spgrid_id
* Sequence within each block (1–10) and month
bysort block spgrid_id (ym): gen month = _n
* Generate treatment indicator based on randomized treatment start times
gen treatment = 0
replace treatment = 1 if (block == 1 & month >= 6)
replace treatment = 1 if (block == 2 & month >= 8)
replace treatment = 1 if (block == 3 & month >= 12)

Comment