I have 4000 observations, 1000 observations each for 4 different months. I have a global macro, treatment
, that I want to randomly assign to my observations. I want to separately do this for each month. treatment
takes on 35 values. For each month, I want the first 20 values of treatment
to each have 29 observations and to have the last 15 values of treatment
to each have 28 observations each. That makes 1000 total/month. For example, the first 1000 observations are Jan
. I want A01
to be randomly assigned to 29 observations within Jan
. ... And G05
to be randomly assigned to 28 observations of Jan
.
clear
set obs 4000
gen ID = _n
gen month = "Jan" if _n<=1000
replace month = "Feb" if _n>=1001 & _n<=2000
replace month = "Mar if _n>=2001 & _n<=3000
replace month = "Apr" if _n>=3001 & _n<=4000
*Create treatment
global letters A B C D E F G
global numbers 01 02 03 04 05
global treatment ""
foreach i in $letters {
foreach j in $numbers {
global treatment $treatment `i'`j'
}
}
At this point, what is the best way to randomly assign treatment
to observations - separately for each month?
The way that I thought of would be to create a runiform() variable; sort by this variable and also by month; then go about allocating the first value of treatment
to the first 29 observations and so on. But I am hoping there is a better way than this.
That's probably how I'd do it:
clear
set more off
*----- example data -----
set obs 2000
gen month = cond(_n <= 1000, 1, 2)
*----- what you want -----
bysort month: gen orig = _n
set seed 3596
gen runi = runiform()
bysort month (runi): egen treat1 = seq() if orig <= 580, from(1) to(20)
by month: egen treat2 = seq() if orig >= 581, from(21) to(35)
gen treat = max(treat1, treat2)
sort orig
drop treat?
tab treat month
Then all you need to do is map the integers 1-35 to treatments which you can do with value labels. I've used numbers in my example, but it is easy to make it more general.
There are other ways of creating the sequences, which you can check in the Stata FAQ pages.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments