sort
Puts the rows in order, smallest first.
What we have
- a stable ascending sort on any variable list
Coming later
- Stata's
bysort x (y):, which sorts within the group on the same line — usesortthenby
How you write it
sort varlist
Square brackets mean optional. A vertical bar means choose one.
What it does
sort state sector orders by state, and within each state by sector. Rows that tie keep the order they were already in (a stable sort), so sorting twice does not shuffle things behind your back.
Several commands need sorted data to mean what you expect — by groups and the _n row number most of all.
Watch out. It only sorts upwards. For largest-first, use
gsort.Try it
Every example below was run after sysuse vira.sample02, clear.
. sort state sector
The same thing in pandas and in R
pandas
df = df.sort_values(['state', 'sector']).reset_index(drop=True)
R
library(dplyr) df <- df %>% arrange(state, sector) # This R was run in a real R (4.6.1) and gave the same numbers.