Title stata.com
gsort — Ascending and descending sort
Syntax Menu Description Options
Remarks and examples Also see
Syntax
gsort [ + | - ] varname
[ + | - ] varname . . .
, generate(newvar) mfirst
Menu
Data > Sort
Description
gsort arranges observations to be in ascending or descending order of the specified variables and
so differs from sort in that sort produces ascending-order arrangements only; see [D] sort.
Each varname can be numeric or a string.
The observations are placed in ascending order of varname if + or nothing is typed in front of the
name and are placed in descending order if - is typed.
Options
generate(newvar) creates newvar containing 1, 2, 3, . . . for each group denoted by the ordered
data. This is useful when using the ordering in a subsequent by operation; see [U] 11.5 by varlist:
construct and examples below.
mfirst specifies that missing values be placed first in descending orderings rather than last.
Remarks and examples stata.com
gsort is almost a plug-compatible replacement for sort, except that you cannot specify a general
varlist with gsort. For instance, sort alpha-gamma means to sort the data in ascending order of
alpha, within equal values of alpha; sort on the next variable in the dataset (presumably beta),
within equal values of alpha and beta; etc. gsort alpha-gamma would be interpreted as gsort
alpha -gamma, meaning to sort the data in ascending order of alpha and, within equal values of
alpha, in descending order of gamma.
Example 1
The difference in varlist interpretation aside, gsort can be used in place of sort. To list the 10
lowest-priced cars in the data, we might type
. use http://www.stata-press.com/data/r13/auto
. gsort price
. list make price in 1/10
1