Section 3.6 arrange and sort rows
One of the most commonly performed data-wrangling tasks is to sort a data frame’s rows in the alphanumeric order of one of the variables. The
arrange() function allows us to sort/reorder a data frame’s rows according to the values of the specified variable.
Suppose we are interested in determining the most frequent destination airports for all domestic flights departing from New York City in 2023:
freq_dest <- flights |>
group_by(dest) |>
summarize(num_flights = n())
freq_dest
# A tibble: 118 × 2 dest num_flights <chr> <int> 1 ABQ 228 2 ACK 916 3 AGS 20 4 ALB 1581 5 ANC 95 6 ATL 17570 7 AUS 4848 8 AVL 1617 9 AVP 145 10 BDL 701 # ℹ 108 more rows
Observe that by default the rows of the resulting
freq_dest data frame are sorted in alphabetical order of destination. Say instead we would like to see the same data, but sorted from the most to the least number of flights (num_flights) instead:
freq_dest |>
arrange(num_flights)
# A tibble: 118 × 2 dest num_flights <chr> <int> 1 LEX 1 2 AGS 20 3 OGG 20 4 SBN 24 5 HDN 28 6 PNS 71 7 MTJ 77 8 ANC 95 9 VPS 109 10 AVP 145 # ℹ 108 more rows
This is, however, the opposite of what we want. The rows are sorted with the least frequent destination airports displayed first. This is because
arrange() always returns rows sorted in ascending order by default. To switch the ordering to be in “descending” order instead, we use the desc() function as so:
freq_dest |>
arrange(desc(num_flights))
# A tibble: 118 × 2 dest num_flights <chr> <int> 1 BOS 19036 2 ORD 18200 3 MCO 17756 4 ATL 17570 5 MIA 16076 6 LAX 15968 7 FLL 14239 8 CLT 12866 9 DFW 11675 10 SFO 11651 # ℹ 108 more rows
