The arrange() function with a single column

arrange(<my_data_frame>, <column_one>)
arrange(<my_data_frame>, <column_one>, <column_two>, ...)
View Interactive Version

The arrange() function orders the rows of a data frame. It takes a data frame or a tibble as the first parameter and the names of the columns based on which the rows should be ordered as additional parameters. Let’s assume, we want to answer the question: Which states had the highest percentage of Republican voters in the 2016 US presidential election? To answer this question, in the following example we use the pres_results_2016 data frame, containing information only for the 2016 US presidential election. We arrange() the data frame based on the rep column (Republican votes in percentage):

Input
arrange(pres_results_2016, rep)
Output
# A tibble: 51 x 6
   year state total_votes   dem    rep  other
  <dbl> <chr>       <dbl> <dbl>  <dbl>  <dbl>
1  2016 DC         312575 0.905 0.0407 0.0335
2  2016 HI         437664 0.610 0.294  0.0958
3  2016 VT         320467 0.557 0.298  0.0737
# … with 48 more rows

As you can see in the output, the data frame is sorted in an ascending order based on the rep column. However, we would prefer to have the results in a descending order, so that we can instantly see the state with the highest rep percentage. To sort a column in a descending order, all we need to do is apply the desc() function on the given column inside the arrange() function:

Input
arrange(pres_results_2016, desc(rep))
Output
# A tibble: 51 x 6
   year state total_votes   dem   rep  other
  <dbl> <chr>       <dbl> <dbl> <dbl>  <dbl>
1  2016 WV         713051 0.265 0.686 0.0489
2  2016 WY         258788 0.216 0.674 0.0830
3  2016 OK        1452992 0.289 0.653 0.0575
# … with 48 more rows

Arranging is not only possible on numeric values, but on character values as well. In that case, dplyr sorts the rows in alphabetic order. We can arrange character columns just like numeric ones:

Input
arrange(pres_results_2016, state)
Output
# A tibble: 51 x 6
   year state total_votes   dem   rep  other
  <dbl> <chr>       <dbl> <dbl> <dbl>  <dbl>
1  2016 AK         318608 0.366 0.513 0.0928
2  2016 AL        2123372 0.344 0.621 0.0254
3  2016 AR        1130635 0.337 0.606 0.0577
# … with 48 more rows
Sort data frames by columns