Reordering factors

Categorical Data in the Tidyverse

Emily Robinson

Data Scientist

A bar chart with the response on the x-axis, count on the y-axis, and the title "how often do you use NLP at work?" The bars, from left to right, are most of the time, often, rarely, and sometimes.

Categorical Data in the Tidyverse

Corrected graph

ggplot(aes(nlp_frequency, 
            x = fct_relevel(response, 
            "Rarely", "Sometimes", "Often", "Most of the time"))) + 
        geom_bar()

The same bar chart as before, now ordered, from left to right, rarely, sometimes, often, most of the time.

Categorical Data in the Tidyverse

fct_reorder()

nlp_frequency %>%
    pull(response) %>%
    levels()
[1] "Most of the time" "Often" "Rarely" "Sometimes"       
nlp_frequency %>%
    mutate(response = fct_relevel(response, 
            "Often", "Most of the time")) %>%
    pull(response) %>%
    levels()
[1] "Often" "Most of the time" "Rarely" "Sometimes"
Categorical Data in the Tidyverse

Additional arguments

nlp_frequency %>%
    mutate(response = fct_relevel(response, 
            "Often", "Most of the time", after = 2)) %>%
            pull(response) %>%
            levels()
nlp_frequency %>%
    mutate(response = fct_relevel(response, 
            "Often", "Most of the time", after = Inf) %>%
    pull(response) %>%
    levels()
[1] "Rarely" "Sometimes" "Often" "Most of the time"
Categorical Data in the Tidyverse

Let's practice!

Categorical Data in the Tidyverse

Preparing Video For Download...