Stata 11 help for sort

help sort dialog: sort -------------------------------------------------------------------------------

Title

[D] sort -- Sort data

Syntax

sort varlist [in] [, stable]

Menu

Data > Sort > Ascending sort

Description

sort arranges the observations of the current data into ascending order based on the values of the variables in varlist. There is no limit to the number of variables in the varlist. Missing numeric values (see missing) are interpreted as being larger than any other number, so they are placed last with . < .a < .b < ... < .z. When you sort on a string variable, however, null strings are placed first. The dataset is marked as being sorted by varlist unless in range is specified. If in range is specified, only those observations are rearranged. The unspecified observations remain in the same place.

Option

stable specifies that observations with the same values of the variables in varlist keep the same relative order in the sorted data that they had previously. For instance, consider the following data:

x b 3 1 1 2 1 1 1 3 2 4

Typing sort x without the stable option produces one of the following 6 orderings.

x b | x b | x b | x b | x b | x b 1 2 | 1 2 | 1 1 | 1 1 | 1 3 | 1 3 1 1 | 1 3 | 1 3 | 1 2 | 1 1 | 1 2 1 3 | 1 1 | 1 2 | 1 3 | 1 2 | 1 1 2 4 | 2 4 | 2 4 | 2 4 | 2 4 | 2 4 3 1 | 3 1 | 3 1 | 3 1 | 3 1 | 3 1

Without the stable option, the ordering of observations with equal values of varlist is randomized. With sort x, stable, you will always get the first ordering and never the other five.

If your intent is to have the observations sorted first on x and then on b within tied values of x (the fourth ordering above), you should type sort x b rather than sort x, stable.

stable is seldom used, and, when specified, causes sort to execute more slowly.

Examples

Setup . sysuse auto . keep make mpg weight

Arrange observations into ascending order based on the values of mpg . sort mpg

Same as above, but for observations with the same values of mpg, keep them in the same relative order in the sorted data as they had previously . sort mpg, stable

List the 5 cars with the lowest mpg . list make mpg in 1/5

List the 5 cars with the highest mpg . list make mpg in -5/L

Arrange observations into ascending order based on the values of mpg, and within each mpg category arrange observations into ascending order based on the values of weight . sort mpg weight

List the 8 cars with the lowest mpg, and within each mpg category with the lowest weight . list in 1/8

Also see

Manual: [D] sort

Help: [D] describe, [D] gsort


© Copyright 1996–2009 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index