Learn tidyverse · 5/13

Reshaping Data for Analysis (tidyr)

7 min read

Reshaping Data for Analysis with tidyr 🧹

Welcome to the data janitor's closet! 🧽

If you talk to any Data Scientist in the industry, they will whisper a painful truth to you: 80% of data analysis is just cleaning and reshaping data. The fun machine learning stuff is just the cherry on top. If your data structure is bad, your analysis is doomed.

In the tidyverse, the package responsible for organizing the geometry of your data is called tidyr.

🛠️ Setup

Before we start bending matrices, let's load the core library. tidyr comes bundled with the tidyverse.

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

library(tidyverse)

1. pivot_longer(): Making Wide Data Tidy 📉

The Definition

Wide Data: A dataset where a single variable is spread across multiple columns.
Long Data (Tidy): A dataset where each variable has its own column, and each observation has its own row.

The Problem

Imagine you get a spreadsheet from the Sales Department. It looks like this:

Product 2021 2022 2023
Widget A 100 120 140
Widget B 80 90 95

This is Wide Data. It is great for human eyes because it is compact.
However, it is terrible for computers. Why?

  1. "Year" is a variable, but it's hiding in the column headers.
  2. "Sales" is a variable, but it's spread across three columns.
  3. If you try to plot this in ggplot2, you can't map x = Year because "Year" isn't a column—it's three columns.

The Solution: pivot_longer()

We need to rotate the table so "Year" becomes a column and "Sales" becomes a column. This increases the number of rows (makes it longer).

Industry Practice

This is the most common reshaping task. You will use this constantly when moving from Excel exports to R analysis.

r
# 1. Create the messy wide data
sales_wide <- tribble(
  ~Product, ~"2021", ~"2022", ~"2023", # Quoted numbers because column names can't start with numbers usually
  "Widget A", 100, 120, 140,
  "Widget B", 80, 90, 95
)

# 2. Pivot it longer
sales_long <- sales_wide %>%
  pivot_longer(
    cols = c("2021", "2022", "2023"), # Which columns are we melting?
    names_to = "Year",                # What should we call the new column for headers?
    values_to = "Sales"               # What should we call the new column for the numbers?
  )

print(sales_long)

Output:

text
# A tibble: 6 × 3
  Product  Year  Sales
  <chr>    <chr> <dbl>
1 Widget A 2021    100
2 Widget A 2022    120
3 Widget A 2023    140
4 Widget B 2021     80
5 Widget B 2022     90
6 Widget B 2023     95

Now, Year is a clean column we can filter, group by, or plot!

Funny Fact: Before pivot_longer(), there was a function called gather(). It was confusing. Before that, melt(). Data scientists have been trying to name this operation correctly for decades. pivot_longer is the current champion. 🏆


2. pivot_wider(): Spreading Data for Summaries 📈

The Definition

Widening: The inverse of lengthening. Taking values from a column and turning them into column headers.

The Problem

You have done your analysis on "Tidy/Long" data, but now your manager wants a report. They don't want to scroll through 10,000 rows. They want a summary table to copy-paste into a PowerPoint slide.

Or, perhaps you are doing Machine Learning. Many algorithms require "One-Hot Encoding" or distinct features in columns, not stacked in rows.

The Solution: pivot_wider()

We take a key column and spread its unique values across the top as headers.

Industry Practice

Use this at the end of your analysis pipeline for reporting, or during feature engineering.

r
# Let's take our sales_long data and turn it back into a report format
# But maybe we want Products as columns this time?

report_table <- sales_long %>%
  pivot_wider(
    names_from = Product,  # Get new column names from here
    values_from = Sales    # Get the numbers to fill cells from here
  )

print(report_table)

Output:

text
# A tibble: 3 × 3
  Year  `Widget A` `Widget B`
  <chr>      <dbl>      <dbl>
1 2021         100         80
2 2022         120         90
3 2023         140         95

See that? We completely transposed the matrix logic.


3. separate() and unite(): Splitting and Combining ✂️

The Definition

Separate: Splitting one character column into multiple columns based on a delimiter (like a comma, dash, or underscore).
Unite: Pasting multiple columns together into one.

The Problem

Data entry systems are lawless wastelands.

  • Problem A: You get a column called rate containing "100/year". You can't do math on "100/year". You need "100" (number) and "year" (unit).
  • Problem B: You have Century ("19") and Year ("99") and you need a proper date ("1999").

The Solution

Use separate() to slice strings and unite() to glue them.

Industry Practice

You will frequently see this with Date-Time strings (e.g., "2023-10-14_10:00") or Location strings ("London, UK").

r
# The Messy Data
employees <- tibble(
  id = 1:2,
  name = c("Doe, John", "Smith, Jane"),
  job_code = c("Eng_Senior", "Des_Junior")
)

# Cleaning it up
cleaned_employees <- employees %>%
  # 1. Split name into First and Last
  separate(
    col = name,
    into = c("Last_Name", "First_Name"),
    sep = ", " 
  ) %>%
  # 2. Split job_code into Dept and Level
  separate(
    col = job_code,
    into = c("Department", "Level"),
    sep = "_"
  )

print(cleaned_employees)

Output:

text
# A tibble: 2 × 5
     id Last_Name First_Name Department Level 
  <int> <chr>     <chr>      <chr>      <chr> 
1     1 Doe       John       Eng        Senior
2     2 Smith     Jane       Des        Junior

Now, let's reverse it with unite(). Imagine we need a unique ID string.

r
employees_united <- cleaned_employees %>%
  unite(
    col = "unique_slug",    # New column name
    c(Department, Level),   # Columns to combine
    sep = "-"               # The glue
  )

4. Handling Missing Values: drop_na(), replace_na(), and fill() 🕵️‍♂️

The Definition

NA: Not Available. The bane of existence for R code. 10 + NA = NA. One missing value can poison an entire calculation.

The Problem

Real-world data is full of holes.

  1. A sensor broke for an hour.
  2. A user didn't answer a survey question.
  3. Excel spreadsheets often leave cells blank to imply "same as above" (Implicit Missingness).

The Solutions

A. drop_na(): The Nuclear Option ☢️

If a row has missing data, delete the entire row.

  • Use when: You have plenty of data and cannot risk guessing the missing values.
r
df_messy <- tibble(
  x = c(1, 2, NA),
  y = c("A", NA, "C")
)

df_clean <- df_messy %>% drop_na()
# Result: Only row 1 remains. Row 2 and 3 are gone.

B. replace_na(): The Safe Patch 🩹

Replace NA with a specific value (like 0 for sales, or "Unknown" for names).

r
df_patched <- df_messy %>%
  replace_na(list(x = 0, y = "Unknown"))

C. fill(): The "Excel Fix" ⬇️

In Excel, people often type a category in the top cell and leave the cells below it blank, assuming you know they belong to that category. In R, those blanks become NA.
fill() replaces NA with the most recent non-NA value from above (Last Observation Carried Forward).

r
# Typical Excel export format
inventory <- tibble(
  Category = c("Electronics", NA, NA, "Furniture", NA),
  Item = c("Laptop", "Mouse", "Cable", "Chair", "Desk")
)

# Fill the Category down
inventory_filled <- inventory %>%
  fill(Category, .direction = "down")

print(inventory_filled)

Output:

text
# A tibble: 5 × 2
  Category    Item  
  <chr>       <chr> 
1 Electronics Laptop
2 Electronics Mouse 
3 Electronics Cable 
4 Furniture   Chair 
5 Furniture   Desk  

Warning: Be careful with fill(). If the data isn't sorted correctly by time or group, you might fill a missing value with data from a completely unrelated record!


🧠 Summary Checklist

  1. Too many columns for one variable? →\rightarrow pivot_longer()
  2. Need a summary matrix? →\rightarrow pivot_wider()
  3. Two variables stuck in one cell? →\rightarrow separate()
  4. Need to combine columns? →\rightarrow unite()
  5. Blank cells "meaning" the value above? →\rightarrow fill()

📚 References & Further Reading

Challenge

You are given a messy sales data tibble named messy_sales_data. Your task is to perform a series of data cleaning and reshaping operations using tidyr and other tidyverse functions to produce a final summary report.

Your pipeline should perform the following steps in order:

  1. Start with the messy_sales_data tibble.
  2. The region column has implicit missing values. Fill these NAs by carrying forward the last observed non-missing value from the rows above.
  3. Remove any rows from the dataset that have a missing product_id.
  4. The data is in a "wide" format with sales for different years in separate columns. Reshape it into a "long" format. The year information from the sales_2022 and sales_2023 columns should be placed in a new column called year, and their corresponding values should go into a new column called sales.
  5. After pivoting, you'll notice some sales values are NA. Replace all missing sales values with 0.
  6. The product_id column contains two pieces of information. Separate it into two new columns, category and id, using the hyphen - as the delimiter. The original product_id column should be removed.
  7. Finally, create a summary report. The report should be a wide tibble with each product category as a row. It must have columns for sales in 2022 and 2023. The values in these cells should be the sum of all sales for that category in the respective year.

Expected result

Your final output should be a tibble that summarizes the total sales per category for each year. It should be the result of all the data manipulation steps described in the instructions.

  • The final tibble must have 3 rows and 3 columns.
  • The columns must be named category, 2022, and 2023.
  • The values in the 2022 and 2023 columns must be the total calculated sales for each category in that year.

Your final tibble should look exactly like this:

apache
# A tibble: 3 × 3
  category `2022` `2023`
  <chr>     <dbl>  <dbl>
1 APPA       2200   2100
2 ELEC       1500   3050
3 FURN       1500   1800
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.