dplyr Tutorial

Clean, transform and summarise data with dplyr

Practical lessons on filter, mutate, group_by, joins and more — with sample data and exercises.

dplyr cheat sheet Get help with your data

dplyr arrange(): How to Sort Data in R

Updated

arrange() reorders the rows of a data frame. Sort by one column, break ties with a second, and flip the direction with desc(). It is the quickest way to find the biggest, smallest, first or last.

What does arrange() do?

arrange() changes the order of rows. It does not add, remove or change any values. You give it a data frame and one or more columns to sort by:

arrange(data, column)

Piped, as in the pipe operator lesson:

data |> arrange(column)

By default, rows are sorted from smallest to largest, or from A to Z. This lesson is part of our dplyr tutorial. It builds on dplyr filter (choosing rows) and dplyr mutate (creating columns).

Sample data

The same ten US cities again, with five columns. Populations are rounded Census figures in thousands, for practice. Notice the rows start in an arbitrary order: New York first, Austin last.

library(dplyr)

cities <- tibble(
  city  = c("New York", "Los Angeles", "Chicago", "Houston", "Phoenix",
            "Philadelphia", "San Antonio", "San Diego", "Dallas", "Austin"),
  state = c("NY", "CA", "IL", "TX", "AZ", "PA", "TX", "CA", "TX", "TX"),
  region = c("Northeast", "West", "Midwest", "South", "West",
             "Northeast", "South", "West", "South", "South"),
  population_2010 = c(8175, 3793, 2696, 2099, 1446, 1526, 1327, 1307, 1198, 790),
  population_2020 = c(8804, 3899, 2746, 2305, 1608, 1604, 1435, 1387, 1304, 962)
)
cities
citystateregionpopulation_2010population_2020
New YorkNYNortheast81758804
Los AngelesCAWest37933899
ChicagoILMidwest26962746
HoustonTXSouth20992305
PhoenixAZWest14461608
PhiladelphiaPANortheast15261604
San AntonioTXSouth13271435
San DiegoCAWest13071387
DallasTXSouth11981304
AustinTXSouth790962

Sort a column ascending

Which city is the smallest? Sort by the 2020 population:

cities |> arrange(population_2020)
citystateregionpopulation_2010population_2020
AustinTXSouth790962
DallasTXSouth11981304
San DiegoCAWest13071387
San AntonioTXSouth13271435
PhiladelphiaPANortheast15261604
PhoenixAZWest14461608
HoustonTXSouth20992305
ChicagoILMidwest26962746
Los AngelesCAWest37933899
New YorkNYNortheast81758804

The rows now run from Austin (962) at the top to New York (8804) at the bottom. Smallest first is called ascending order, and it is the default.

Sort descending with desc()

To arrange in descending order, wrap the column in desc():

cities |> arrange(desc(population_2020))
citystateregionpopulation_2010population_2020
New YorkNYNortheast81758804
Los AngelesCAWest37933899
ChicagoILMidwest26962746
HoustonTXSouth20992305
PhoenixAZWest14461608
PhiladelphiaPANortheast15261604
San AntonioTXSouth13271435
San DiegoCAWest13071387
DallasTXSouth11981304
AustinTXSouth790962

Now the biggest city comes first. You may also see arrange(-population_2020) with a minus sign. It works for numbers only, while desc() also works for text and dates, so prefer desc().

Sort text alphabetically

Sorting a text column puts it in alphabetical order:

cities |> arrange(city)
citystatepopulation_2020
AustinTX962
ChicagoIL2746
DallasTX1304
HoustonTX2305
Los AngelesCA3899
New YorkNY8804
PhiladelphiaPA1604
PhoenixAZ1608
San AntonioTX1435
San DiegoCA1387

Use desc(city) to go from Z to A. One detail for later: since dplyr 1.1.0, text is sorted by plain character code by default, so all capital letters come before all lowercase ones ("Zebra" before "apple"). City names all start with capitals, so you will not notice it here. Mixed-case data can behave surprisingly. See the common mistakes table.

Sort by multiple columns

To sort by multiple columns in R, list them in order of importance. Here, sort by region first, and inside each region put the largest city first:

cities |> arrange(region, desc(population_2020))
citystateregionpopulation_2010population_2020
ChicagoILMidwest26962746
New YorkNYNortheast81758804
PhiladelphiaPANortheast15261604
HoustonTXSouth20992305
San AntonioTXSouth13271435
DallasTXSouth11981304
AustinTXSouth790962
Los AngelesCAWest37933899
PhoenixAZWest14461608
San DiegoCAWest13071387

The regions are alphabetical (Midwest, Northeast, South, West), and within each region the populations go from big to small. Each column can have its own direction: here region is ascending and population_2020 is descending.

Break ties

When two rows have the same value, arrange() keeps them in their original order. Sort by state alone and the four Texas cities stay in the order they appeared in the data:

cities |> arrange(state)
citystateregionpopulation_2010population_2020
PhoenixAZWest14461608
Los AngelesCAWest37933899
San DiegoCAWest13071387
ChicagoILMidwest26962746
New YorkNYNortheast81758804
PhiladelphiaPANortheast15261604
HoustonTXSouth20992305
San AntonioTXSouth13271435
DallasTXSouth11981304
AustinTXSouth790962

To control the order inside a tie, add a second column. This sorts by state and then by population, smallest first:

cities |> arrange(state, population_2020)
citystateregionpopulation_2010population_2020
PhoenixAZWest14461608
San DiegoCAWest13071387
Los AngelesCAWest37933899
ChicagoILMidwest26962746
New YorkNYNortheast81758804
PhiladelphiaPANortheast15261604
AustinTXSouth790962
DallasTXSouth11981304
San AntonioTXSouth13271435
HoustonTXSouth20992305

Now Texas runs Austin, Dallas, San Antonio, Houston, and California runs San Diego, then Los Angeles. The second column only matters when the first column has a tie.

Sort by a calculation

You can sort by an expression without creating a column first. Which cities grew fastest, as a ratio of 2020 to 2010 population?

cities |> arrange(desc(population_2020 / population_2010))
citypopulation_2010population_2020
Austin790962
Phoenix14461608
Houston20992305
Dallas11981304
San Antonio13271435
New York81758804
San Diego13071387
Philadelphia15261604
Los Angeles37933899
Chicago26962746

Austin is first, because its population grew by about 22%. Phoenix and Houston follow. If you also want to see the growth figure, create it with mutate() first and sort by the new column.

Sort with missing values (NA)

Missing values are always placed last, whichever direction you choose. Take the small made-up rent table from the filter lesson, where two cities have no rent value:

rent <- tibble(
  city = c("New York", "Chicago", "Houston", "Phoenix", "Austin", "Dallas"),
  median_rent = c(3400, 1900, NA, 1650, 2000, NA)
)
rent |> arrange(median_rent)
citymedian_rent
Phoenix1650
Chicago1900
Austin2000
New York3400
HoustonNA
DallasNA
rent |> arrange(desc(median_rent))
citymedian_rent
New York3400
Austin2000
Chicago1900
Phoenix1650
HoustonNA
DallasNA

In both results, Houston and Dallas stay at the bottom. To put the missing values first, sort by is.na() in descending order, then by the column itself:

rent |> arrange(desc(is.na(median_rent)), median_rent)
citymedian_rent
HoustonNA
DallasNA
Phoenix1650
Chicago1900
Austin2000
New York3400

is.na() gives TRUE for missing rows. Descending order puts TRUE before FALSE, so those rows rise to the top.

Sort in a custom order

Alphabetical order is not always what you want. Suppose you need the regions in the order West, South, Midwest, Northeast. Turn the column into a factor with the levels in your chosen order, and sort by that:

cities |>
  arrange(
    factor(region, levels = c("West", "South", "Midwest", "Northeast")),
    city
  )
citystateregionpopulation_2010population_2020
Los AngelesCAWest37933899
PhoenixAZWest14461608
San DiegoCAWest13071387
AustinTXSouth790962
DallasTXSouth11981304
HoustonTXSouth20992305
San AntonioTXSouth13271435
ChicagoILMidwest26962746
New YorkNYNortheast81758804
PhiladelphiaPANortheast15261604

The first sort key follows your custom order, and city arranges the cities alphabetically within each region.

Sort within groups

On grouped data, arrange() ignores the groups by default and sorts the whole table. Add .by_group = TRUE to sort by the grouping columns first:

cities |>
  group_by(region) |>
  arrange(desc(population_2020), .by_group = TRUE)

This produces the same row order as arrange(region, desc(population_2020)) above, but the result stays grouped. If you are not working with grouped data, simply list the columns as in the multiple-columns example. Grouping is explained in dplyr group_by and summarise.

arrange() in a pipeline

Sorting is usually one step in a longer chain. This lists cities outside Texas, biggest first, with only the columns we need:

cities |>
  filter(state != "TX") |>
  arrange(desc(population_2020)) |>
  select(city, state, population_2020)
citystatepopulation_2020
New YorkNY8804
Los AngelesCA3899
ChicagoIL2746
PhoenixAZ1608
PhiladelphiaPA1604
San DiegoCA1387

To keep just the top few rows after sorting, add slice_head(n = 3). The dplyr slice lesson covers that, including the shortcut slice_max(), which sorts and slices in one step.

Remember that arrange() returns a sorted copy. To keep it, assign it:

cities_sorted <- cities |> arrange(desc(population_2020))

dplyr arrange vs base R

TaskdplyrBase R
Ascendingarrange(cities, population_2020)cities[order(cities$population_2020), ]
Descendingarrange(cities, desc(population_2020))cities[order(cities$population_2020, decreasing = TRUE), ]
Two columnsarrange(cities, region, desc(population_2020))cities[order(cities$region, -cities$population_2020), ]
Sort one vectorx |> sort() (base)sort(c(3, 1, 2))

In base R, order() returns row positions, and you use them to reorder the data frame yourself. sort() only works on a single vector, so it cannot sort a whole data frame. arrange() avoids the repeated cities$ and the trailing comma.

Common mistakes

MistakeWhat happensFix
Forgetting desc()You get smallest first when you wanted the biggestWrap the column: desc(population_2020)
arrange(desc(region, population_2020))Error: desc() takes only one columnUse desc() on each column separately: arrange(desc(region), desc(population_2020))
Columns in the wrong orderThe first column is the main sort key. Swapping them changes the resultPut the most important column first
Expecting the sort to stickThe original data frame remains unsortedAssign: cities <- cities |> arrange(...)
Numbers stored as text"10" is placed before "9", because text sorts character by characterConvert first: mutate(x = as.numeric(x))
Mixed-case text orderCapital letters come before lowercase ones (dplyr 1.1.0 and later)Make the case consistent, or add .locale = "en" (needs the stringi package)
Using sort() on a data frameError saying x must be atomicUse arrange() or order()
Grouped data not sorted by grouparrange() ignores grouping by defaultAdd .by_group = TRUE

Practice exercises

Use the cities and rent tables. Try each one before opening the answer.

Exercise 1

Sort the cities by their 2010 population, smallest first.

Show answer
cities |> arrange(population_2010)
citystateregionpopulation_2010population_2020
AustinTXSouth790962
DallasTXSouth11981304
San DiegoCAWest13071387
San AntonioTXSouth13271435
PhoenixAZWest14461608
PhiladelphiaPANortheast15261604
HoustonTXSouth20992305
ChicagoILMidwest26962746
Los AngelesCAWest37933899
New YorkNYNortheast81758804

Exercise 2

Sort the cities by name from Z to A.

Show answer
cities |> arrange(desc(city))
citystatepopulation_2020
San DiegoCA1387
San AntonioTX1435
PhoenixAZ1608
PhiladelphiaPA1604
New YorkNY8804
Los AngelesCA3899
HoustonTX2305
DallasTX1304
ChicagoIL2746
AustinTX962

Exercise 3

Sort by state from A to Z, and within each state put the biggest 2020 population first.

Show answer
cities |> arrange(state, desc(population_2020))
citystateregionpopulation_2010population_2020
PhoenixAZWest14461608
Los AngelesCAWest37933899
San DiegoCAWest13071387
ChicagoILMidwest26962746
New YorkNYNortheast81758804
PhiladelphiaPANortheast15261604
HoustonTXSouth20992305
San AntonioTXSouth13271435
DallasTXSouth11981304
AustinTXSouth790962

Exercise 4

Find the three cities that gained the most people between 2010 and 2020. Show the city and the gain.

Show answer
cities |>
  mutate(growth = population_2020 - population_2010) |>
  arrange(desc(growth)) |>
  slice_head(n = 3) |>
  select(city, growth)
citygrowth
New York629
Houston206
Austin172

Exercise 5

Sort the rent table with the missing values first, then from the highest rent to the lowest.

Show answer
rent |> arrange(desc(is.na(median_rent)), desc(median_rent))
citymedian_rent
HoustonNA
DallasNA
New York3400
Austin2000
Chicago1900
Phoenix1650

dplyr FAQ

How do I sort a data frame in R with dplyr?

Use arrange() with the column to sort by, for example arrange(cities, population_2020). The default order is ascending, from smallest to largest or A to Z.

How do I arrange in descending order in dplyr?

Wrap the column in desc(): arrange(cities, desc(population_2020)). It works for numbers, text and dates.

How do I sort by multiple columns in dplyr?

List the columns in order of importance, separated by commas: arrange(cities, region, desc(population_2020)). Later columns only break ties in earlier ones.

Where does arrange() put NA values?

Always at the end, whether you sort ascending or descending. To put them first, sort by desc(is.na(column)) before the column itself.

What is the difference between arrange(), order() and sort()?

arrange() sorts the rows of a data frame. order() is base R and returns the positions you use to reorder rows. sort() only works on a single vector, not on a data frame.

Why does my original data frame stay unsorted?

arrange() returns a new, sorted copy and never changes the original. Assign it with <- to keep the sorted version.

Key points

  • arrange() reorders rows. It never changes values or removes rows.
  • The default is ascending. Use desc() for descending order.
  • List several columns to sort by more than one. The first is the main key, and later ones break ties.
  • Missing values always go last. Use desc(is.na(x)) to bring them to the top.
  • You can sort by an expression, or by a factor to get a custom order.
  • The result is a new table, so assign it with <- to keep it.

Next, learn how to change column names with dplyr rename. To sort and take the top rows in one step, see dplyr slice.