I am trying to learn else condition loops in Stata. To do this I'm trying random assignment into treatment and control. However, I keep getting the error: '{' invalid
I can do it normally:
g treat = 0 if random > 0.5
replace treat = 1 if random < 0.5
However, I want to try it out with the else condition. Moreover, additional resources to learn the if condition would also be greatly appreciated. The else condition loop that I am trying:
clear all
// Set the seed for the random number generator
set seed 98034
set obs 10000
// Generate 1000 random numbers between 0 and 1
g random = runiform()
// For each observation, assign it to the treatment group if the random number is less than 0.5, and to the control group otherwise
forvalues i = 1(1)10000 {
g treatment = 1 if random[`i'] < 0.5 {
else {
treatment[`i'] = 0
}
}
}
While gen treatment = runiform() < 0.5
generates two identically sized groups on average, it is not guaranteed that the groups are the same size. Therefore, I think random assignment should be done by random ranking.
clear all
// Set the seed for the random number generator
set seed 98034
set obs 10000
// Assign treatment using 1000 random numbers between 0 and 1
gen rand = runiform()
sort rand
gen treatment = (_n <= _N/2)
tab treatment
Technically, to make the randomization truly reproducible you also need to set the Stata version (for example, version 16
) and stably sort the data (for example isid idvar, sort
) before using runiform()
.