问题
I have the following lottery numbers in a macro:
global lottery 6 9 4 32 98
How can I simulate a variable with 50
observations, where each observation is randomly obtained from the numbers stored in the macro?
The code below produces an error:
set obs 50
global lottery 6 9 4 32 98
g lot=$lottery
invalid '9'
r(198);
回答1:
Here are two similar methods:
clear
set obs 50
set seed 2803
local lottery 6 9 4 32 98
* method 1
generate x1 = ceil(5 * runiform())
tabulate x1
generate y1 = .
forvalues j = 1/5 {
replace y1 = real(word("`lottery'", `j')) if x1 == `j'
}
* method2
set seed 2803
generate x2 = runiform()
generate y2 = cond(x2 <= 0.2, 6, cond(x2 <= 0.4, 9, cond(x2 <= 0.6, 4, cond(x2 <= 0.8, 32, 98))))
tab1 y?
I am assuming that you want equal probabilities, which is not explicit. The principle of setting the seed is crucial for reproducibility. As in @Pearly Spencer's answer, using a local
macro is widely considered (much) better style.
To spell it out: in this answer the probabilities are equal, but the frequencies will fluctuate from sample to sample. In @Pearly’s answer the frequencies are guaranteed equal, given that 50 is a multiple of 5, and randomness is manifest only in the order in which they arrive. This answer is like tossing a die with five faces 50 times; @Pearly’s answer is like drawing from a deck of 50 cards with 5 distinct types.
回答2:
If you want equal frequencies for the 5
values, create the variable holding the numbers as follows:
clear
set obs 50
local lottery 6 9 4 32 98
egen lot = fill(`lottery' `lottery')
list lot in 1 / 10
+-----+
| lot |
|-----|
1. | 6 |
2. | 9 |
3. | 4 |
4. | 32 |
5. | 98 |
|-----|
6. | 6 |
7. | 9 |
8. | 4 |
9. | 32 |
10. | 98 |
+-----+
You then sort on a random variable to shuffle them:
generate random = runiform()
sort random
list lot in 1 / 10
+-----+
| lot |
|-----|
1. | 9 |
2. | 6 |
3. | 9 |
4. | 4 |
5. | 9 |
|-----|
6. | 6 |
7. | 32 |
8. | 6 |
9. | 98 |
10. | 6 |
+-----+
Note that here I use a local macro and only the first ten observations are shown.
来源:https://stackoverflow.com/questions/57999619/random-lottery-numbers-from-macro-to-variable