Appendix E — Extras: Arranging rows in dplyr

E.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)