Sometimes all the data you want is in your data frame, but it’s all unorganized! Step in the handy dandy dplyr function arrange()
! arrange()
will sort the rows of a data frame in ascending order by the column provided as an argument.
For numeric columns, ascending order means from lower to higher numbers. For character columns, ascending order means alphabetical order from A to Z.
Let’s look back at the customers
data frame for your company:
name | age | address | phone |
---|---|---|---|
Martha Jones | 28 | 123 Main St. | 234-567-8910 |
Rose Tyler | 22 | 456 Maple Ave. | 212-867-5309 |
Donna Noble | 35 | 789 Broadway | 949-123-4567 |
Amy Pond | 29 | 98 West End Ave. | 646-555-1234 |
Clara Oswald | 31 | 54 Columbus Ave. | 714-225-1957 |
To arrange the customers in ascending order by name:
customers %>% arrange(name)
- the
customers
data frame is piped intoarrange()
- the column to order by,
name
, is given as an argument - a new data frame is returned with rows in ascending order by
name
arrange()
can also order rows by descending order! To arrange the customers in descending order by age:
customers %>% arrange(desc(age))
- the
customers
data frame is again piped intoarrange()
- the column to order by,
age
, is given as an argument todesc()
, which is then given as an argument toarrange()
- a new data frame is returned with rows in descending order by
age
If multiple arguments are provided to arrange()
, it will order the rows by the column given as the first argument and use the additional columns to break ties in the values of preceding columns.
Instructions
Arrange the rows of artists
in ascending order by group
. Save the result to group_asc
, and view it.
Arrange the rows of artists
in descending order by youtube_subscribers
. Save the result to youtube_desc
, and view it.
Make sure to click the arrows in the rendered notebook to see the entire table!