*! version 1.0 22apr2013

help for rsortVersion 1.0, 22 April 2013

Title

rsort -- Reproducible random sorting of dataset

Syntax

rsort [, options]

Required for reproducible sorting
id(varlist) ID variable/s uniquely identifying observations

seed(#) random number seed to use

Convenience
by(varlist) sort within groups defined by varlist

generate(sortorder) create variable containing new observation number

replace replace existing sortorder

Description

rsort randomly sorts the dataset in memory. This is useful for various situations in
which the sort order of the dataset may affect results. If the id() and seed() options are
used then the same dataset will always be sorted the same way, facilitating reproducible analyses.

Options for rsort

id(varlist) specifies one or more variables that uniquely identify observations within the
dataset. This is required if you wish to reproduce the random sort order reliably in future
analyses. This is because the dataset must start with a definitely reproducible sort order (ie in a
known state) prior to assigning random numbers with which to re-sort the dataset.

seed(#) sets the random number seed to # prior to random sorting. This is usually
also required if you wish to reproduce the random sort order. In some cases you may have already
set the random number seed, in which case you may not need to do so again here. If you want
reproducible results, omit seed() only if you're sure that the random seed will be in the same
state every time rsort is called.

by(varlist) allows you to sort randomly within by-groups defined by varlist. This is a
convenience option that saves you from needing to re-sort the data by varlist after running
rsort, while preserving reproducibly random sorting within those by-groups.

generate(sortorder) creates a new variable sortorder containing the new observation
number in the sorted dataset. If you wish to re-sort the data by one or more variables, but preserve
the random order within the by-groups, you first need to create a new variable containing the sort
order arising from rsort. This option saves you the trouble and creates sortorder for you.
If sortorder already exists you can replace it with the replace option.

Examples

Simple random sort of the auto dataset:

. sysuse auto, clear

. rsort, id(make) seed(12345)

Randomly split the dataset into 2 groups within strata defined by rep78:

. sysuse auto, clear

. rsort, id(make) seed(12345) by(rep78)

. by rep78: gen byte group=mod(_n, 2)

. tab rep78 group, mis

Author

Phil Clayton, ANZDATA Registry, Australia, phil@anzdata.org.au

Also see

Using StataÕs random-number generators, part 2, drawing without replacement:
http://blog.stata.com/2012/08/03/using-statas-random-number-generators-part-2-drawing-without-replacement/