Introduction
Knowing how to generate random numbers can be useful. For example, if you have ordered data that you need to shuffle, random numbers can help you. In this blog entry, we’ll show you to generate random numbers in Stata.
Generate Random Data
set obs 1000
gen random = runiform(0,100)
list in 1/30
This command creates 1,000 values for a variable, random, that vary randomly between 0 and 100):
Now, if you like, you can round the random variable or create a cloned version of it to round.
Using Randomness
Let’s say that you have a sequentially ordered variable called sequence that runs from 1 to 1,000. Use the following code to add this variable and see it alongside your random variable:
gen sequence = _n
list in 1/30
You can now use Stata’s sort command to sort on random, not subject. Afterwards, you will have successfully randomized sequence (and any other values that are associated with sequence). For example, if the sequence variable consists of participant numbers, and there are data associated with each participant, you would now also have randomized the order of these data, although they would still be associated with the correct participants.
sort random
list in 1/30
If you have no additional use for the random variable after using it to randomize the order of the sequence variable, you can drop it:
drop random
BridgeText can help you with all of your statistical analysis needs.