Want to help out or contribute?

If you find any typos, errors, or places where the text may be improved, please let us know by providing feedback either in the feedback survey (given during class) or by using GitHub.

On GitHub open an issue or submit a pull request by clicking the " Edit this page" link at the side of this page.

Appendix F — Extras: Arranging rows in dplyr

F.1 Arranging the rows of your data by column

This is continued from ?sec-data-management.

You may want to sort your rows by a specific column so that values are arranged in ascending or descending order. This can be done using the function called arrange(). Again, arrange() takes the dataset as the first argument, followed by the columns that you wish to arrange data by. By default, arrange() orders in ascending order.

R/learning.R
# Arranging data by age in ascending order
nhanes_small %>%
    arrange(age)

arrange() also arranges parameters of type character alphabetically:

R/learning.R
nhanes_small %>% 
    arrange(education)

If we want to order the column based on descending order, this can be done with desc().

R/learning.R
# Arranging data by age in descending order
nhanes_small %>%
    arrange(desc(age))

You can also order your data by multiple columns. For instance, we could arrange first by education and then by age.

R/learning.R
# Arranging data by education then age in ascending order
nhanes_small %>%
    arrange(education, age)