Learn tidyverse Β· 10/13

Mastering Categorical Data (forcats)

7 min read

Mastering Categorical Data with forcats πŸˆπŸ“Š

Welcome back, data wrangler! Today we are tackling one of the most misunderstood, occasionally frustrating, but absolutely essential characters in the R universe: Factors.

If you have ever plotted a bar chart and wondered why the months of the year were sorted alphabetically (April, August, December...) instead of chronologically, you have fallen victim to the "String vs. Factor" confusion.

We are going to use the forcats package (an anagram for for categoricals). It is part of the core tidyverse, so if you have the tidyverse installed, you are ready to go.


πŸ› οΈ Setup and Installation

Before we dive in, let's make sure your environment is ready. We will be using tidyverse, which automatically loads forcats.

r
# If you haven't installed the tidyverse yet:
install.packages("tidyverse")

# Load the library
library(tidyverse)

Fun Fact: The forcats logo features a cat. Developers love cats. It is a universal constant. 🐈


1. What are Factors? Understanding R's Categorical Class

The Problem: Strings are Dumb

Imagine you have a dataset of T-shirt sizes: "Small", "Medium", "Large".
If you store these as standard character strings (text), R doesn't know that "Small" is smaller than "Large". To R, they are just random letters.

If you sort them, R uses the alphabet:

  1. Large
  2. Medium
  3. Small

This is chaos. We need a way to tell R that these text labels belong to a fixed set of known values and (optionally) have a specific order.

The Concept: Factors

A Factor is R's data structure for categorical data.

Definition: A factor is an integer vector with an associated set of character values called "levels".

Under the hood, R stores factors as numbers (1, 2, 3), but displays them as text ("Small", "Medium", "Large"). The Level is the dictionary that maps the number to the text.

πŸŽ“ Hands-on: Creating a Factor

Let's look at a list of months.

r
# Standard character vector
months_char <- c("Dec", "Apr", "Jan", "Mar")

# Sorting characters (Alphabetical - Not what we want!)
sort(months_char)
# Output: "Apr" "Dec" "Jan" "Mar" 

# Define the valid levels in the correct order
month_levels <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", 
                  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

# Create the factor
months_factor <- factor(months_char, levels = month_levels)

# Sorting the factor (Chronological - Success!)
sort(months_factor)
# Output: Jan Mar Apr Dec

⚠️ The Dangerous Trap

Because factors look like text but act like integers, they can cause bugs if you aren't careful.

r
# Implicit coercion trap
sex <- factor(c("m", "f", "m"))
as.numeric(sex) 
# Output: 2 1 2 (Because "f" is alphabetically before "m", it becomes 1)

Industry Standard: Use factors only when you need a specific order for plotting or modeling, or when the set of values is fixed (like days of the week). For general text processing (like names or addresses), stick to character strings.


2. Reordering Factors: fct_reorder() for Better Plotting

The Problem: The Ugly Bar Chart

You are visualizing the average life expectancy by country. By default, ggplot2 will order the bars alphabetically by country name. Afghanistan will be at the top, Zimbabwe at the bottom.

This makes the chart hard to read. Viewers have to scan up and down to find the highest or lowest values. Good data viz requires sorting by value, not by name.

The Solution: fct_reorder()

This function changes the order of the factor levels based on another variable (usually a numeric one).

Syntax: fct_reorder(.f, .x, .fun = median)

  • .f: The factor you want to reorder (e.g., Country).
  • .x: The values you want to order by (e.g., GDP or Life Expectancy).

πŸŽ“ Hands-on: Fixing the Plot

We will use the built-in gss_cat dataset (a sample from the General Social Survey) provided by forcats.

r
# View the data
glimpse(gss_cat)

# Scenario: We want to plot the average number of TV hours watched by Religion.

# 1. The Bad Way (Alphabetical Order)
gss_cat %>%
  group_by(relig) %>%
  summarise(tvhours = mean(tvhours, na.rm = TRUE)) %>%
  ggplot(aes(tvhours, relig)) +
  geom_col() +
  labs(title = "Hard to read (Alphabetical)")

# 2. The Good Way (Sorted by Value)
gss_cat %>%
  group_by(relig) %>%
  summarise(tvhours = mean(tvhours, na.rm = TRUE)) %>%
  # MAGIC HAPPENS HERE: Reorder religion based on tvhours
  mutate(relig = fct_reorder(relig, tvhours)) %>%
  ggplot(aes(tvhours, relig)) +
  geom_col() +
  labs(title = "Easy to read (Sorted by TV Hours)")

Why this works: The plot is now an ordered staircase. The user can instantly see which religions watch the most and least TV without mental gymnastics.


3. Lumping and Collapsing: Managing Too Many Categories (fct_lump)

The Problem: The "Long Tail" Mess

Real-world data is messy. If you analyze "Job Titles" in a company, you might have:

  • 200 "Software Engineers"
  • 150 "Sales Associates"
  • ...
  • 1 "Chief Happiness Officer"
  • 1 "Underwater Basket Weaver"

If you plot this, you will get a chart with hundreds of tiny bars that are impossible to read. This is high-cardinality data.

The Solution: fct_lump_n()

This function automatically keeps the most frequent categories and bundles everything else into a category called "Other". It's like sweeping the dust under the rug, but for data science! 🧹

πŸŽ“ Hands-on: Cleaning the Tail

Let's look at the relig (religion) column in gss_cat. There are many small groups.

r
# Count existing categories
gss_cat %>% count(relig, sort = TRUE)

# Scenario: We only care about the top 5 religions. Lump the rest.

gss_cat %>%
  mutate(relig_lumped = fct_lump_n(relig, n = 5)) %>%
  count(relig_lumped, sort = TRUE)

Output Interpretation:
You will see the top 5 specific religions, and a massive new category called "Other".

Variations:

  • fct_lump_n(x, n): Keep top n.
  • fct_lump_min(x, min): Keep groups that appear at least min times.
  • fct_lump_prop(x, prop): Keep groups that make up at least prop (e.g., 0.1 or 10%) of the data.

Industry Tip: Always check what ended up in "Other". If "Other" becomes your largest category, your analysis might be too vague!


4. Recoding Levels: Renaming and Dropping Unused Levels

The Problem: Dirty Data Labels

Sometimes data comes in ugly.

  • "United States"
  • "USA"
  • "US"
  • "u.s."

Or perhaps the data is technically correct but not presentation-ready (e.g., partyid "Independent, near dem" is too long for a chart label).

The Solution: fct_recode()

This allows you to manually rename specific levels.

Syntax: fct_recode(factor, "New Name" = "Old Name")

πŸŽ“ Hands-on: Renaming for Clarity

Let's clean up the partyid column in gss_cat to make it simpler.

r
# Check original levels
levels(gss_cat$partyid)

# Simplify the political parties
gss_cat %>%
  mutate(party_simple = fct_recode(partyid,
    "Republican" = "Strong republican",
    "Republican" = "Not str republican",
    "Democrat"   = "Strong democrat",
    "Democrat"   = "Not str democrat",
    "Independent"= "Ind,near rep",
    "Independent"= "Ind,near dem",
    "Independent"= "Independent"
  )) %>%
  count(party_simple)

Notice how we mapped multiple old levels to a single new level ("Strong republican" and "Not str republican" both became "Republican"). This effectively collapses categories manually.

Bonus: fct_drop()

Sometimes, you filter your data, but the factor still remembers the old options.

r
# Filter only for Democrats
only_dems <- gss_cat %>% filter(partyid == "Strong democrat")

# The factor still "knows" about Republicans, even if count is 0
levels(only_dems$partyid) 

# Clean up empty levels (Ghostbusting πŸ‘»)
only_dems$partyid <- fct_drop(only_dems$partyid)

Why this matters: If you don't use fct_drop(), your bar charts will have empty spaces for categories that don't exist in your filtered data.


πŸ“š Summary & Best Practices

  1. Factors are for fixed sets: Use them for categorical variables used in models and plots. Use strings for free text.
  2. Order matters: Use fct_reorder() to make your plots readable (sort by value, not alphabet).
  3. Hide the mess: Use fct_lump() to aggregate rare categories into "Other".
  4. Be explicit: Use fct_recode() to fix typos or shorten labels for presentation.

Data cleaning is 80% of the job. forcats turns that 80% from a headache into a breeze.


πŸ”— References & Further Reading

Challenge

You are given a tibble survey_data containing responses about favorite programming languages and the number of projects developers have completed with them. The language column is messy and needs to be cleaned before it can be used for plotting.

Your task is to perform a three-step transformation on the language column using the forcats package. The final transformed tibble should be assigned to a new variable called cleaned_survey_data.

Your Tasks:

  1. Recode Inconsistent Levels: The language column uses both "JS" and "JavaScript". Use fct_recode() to consolidate these, making "JavaScript" the standard name.
  2. Lump Infrequent Levels: The dataset contains several languages with few responses. To simplify a potential plot, use fct_lump_n() to keep only the top 3 most frequent languages and group all others into an "Other" category.
  3. Reorder by a Numeric Value: For an effective visualization, the languages should be ordered by developer experience. Use fct_reorder() to arrange the language factor levels based on the median value of the projects column.

Chain these operations together, starting with the survey_data tibble.

Expected result

The cleaned_survey_data variable should be a tibble where the language column is a factor that has been correctly recoded, lumped, and reordered.

When you inspect the levels of the factor using levels(cleaned_survey_data$language), the output should be a character vector with the following levels in this specific order:

csharp
[1] "Other"      "R"          "JavaScript" "Python"

This order reflects sorting the categories by the ascending median number of projects:

  • Other: median of 2 projects
  • R: median of 6 projects
  • JavaScript: median of 10.5 projects
  • Python: median of 25 projects
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.