Stata 15 help for sort

[D] sort -- Sort data

Syntax

sort varlist [in] [, stable]

Menu

Data > 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 and uppercase letters come before lowercase letters.

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 six 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

Arrange observations into alphabetical order based on the value of make . sort make

For most purposes, this method of sorting is sufficient. It is possible to override Stata's sort logic. See [U] 12.4.2.5 Sorting strings containing Unicode characters for information about ordering strings in a language-sensitive way. We do not recommend that you do this.


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