UCLA Academic Technology Services HomeServicesClassesContactJobs
Search

Stata FAQ
How can I randomly assign observations to groups in Stata?

The trick here is to create a random variable, sort the dataset by that random variable, and then assign the observations to the groups. Let's use the hsb2 dataset as an example by randomly assigning 50 observations to each of four groups.
use http://www.ats.ucla.edu/stat/stata/notes/hsb2, clear

generate rannum = uniform()
sort rannum
generate grp = .
replace grp = 1 in 1/50
replace grp = 2 in 51/100
replace grp = 3 in 101/150
replace grp = 4 in 151/200

tabulate grp

        grp |      Freq.     Percent        Cum.
------------+-----------------------------------
          1 |         50       25.00       25.00
          2 |         50       25.00       50.00
          3 |         50       25.00       75.00
          4 |         50       25.00      100.00
------------+-----------------------------------
      Total |        200      100.00
      
sort id
list id grp in 1/20

            id        grp 
  1.         1          2  
  2.         2          3  
  3.         3          2  
  4.         4          3  
  5.         5          2  
  6.         6          3  
  7.         7          1  
  8.         8          2  
  9.         9          2  
 10.        10          4  
 11.        11          1  
 12.        12          1  
 13.        13          4  
 14.        14          2  
 15.        15          2  
 16.        16          1  
 17.        17          3  
 18.        18          2  
 19.        19          3  
 20.        20          1 
Of course, when you try this the grp number for each id will be in a different pattern because we are using a random process to assign observations to groups.

For more information

See the Stata manual or Stata Help for functions.

How to cite this page

Report an error on this page

UCLA Researchers are invited to our Statistical Consulting Services
We recommend others to our list of Other Resources for Statistical Computing Help
These pages are Copyrighted (c) by UCLA Academic Technology Services


The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California