Learn R · 8/15

Data Tidying with tidyr

7 min read

Data Tidying with tidyr 🧹

Welcome to the wonderful world of data tidying! It may not sound like the most glamorous part of data analysis, but trust me, getting your data in order is a secret superpower. It's the difference between a frustrating, hair-pulling analysis and a smooth, insightful one. In this guide, we'll explore the tidyr package, a core member of the tidyverse, which provides a fantastic set of tools for cleaning up your messy data.

First things first, let's get tidyr installed and loaded into our R session. If you already have the tidyverse installed, you're good to go.

r
# Install and load the tidyr package
install.packages("tidyr")
library(tidyr)

The Tidy Data Concept: Long vs. Wide Formats 📜

The Problem: Imagine you have a spreadsheet where each column represents a month, and the rows are different products. This is easy for a human to read at a glance, but for a computer trying to perform calculations, it can be a nightmare. This is a classic example of "untidy" or "wide" data.

The Solution: Tidy data is a standardized way of organizing data that makes it easier for computers to work with. The core principles of tidy data are:

  • Each variable forms a column.
  • Each observation forms a row.
  • Each type of observational unit forms a table.

Think of it like this: in a tidy dataset, every row tells you about a single observation, and every column tells you something specific about that observation.

Long vs. Wide Formats:

  • Wide Format: This format is often more intuitive for humans to read and is common in reports and data entry. It typically has a unique identifier for each row, and then multiple columns representing different variables or time points for that identifier.
  • Long Format: This format is generally preferred for data analysis in R. It has more rows and fewer columns. Each row represents a single observation, with one column for the value and another to identify what that value represents. This structure is more flexible for plotting and modeling.

Let's look at a simple example:

Wide Data:

Country 2024 2025
USA 350 360
Canada 40 42

Long Data:

Country Year Population
USA 2024 350
USA 2025 360
Canada 2024 40
Canada 2025 42

See the difference? The long format is more "machine-friendly."

Reshaping Data: pivot_longer() and pivot_wider() 🔄

The Problem: Your data is in the wrong shape! You have wide data and need it to be long for your analysis, or you have long data and need to present it in a wider format for a report.

The Solution: tidyr provides two powerful functions for this: pivot_longer() and pivot_wider(). These functions are the modern replacements for the older gather() and spread() functions.

pivot_longer(): From Wide to Long

This function makes your dataset "longer" by increasing the number of rows and decreasing the number of columns. It's incredibly useful for tidying up data that's been recorded in a wide format.

Example:

Let's say we have some data on fish catches for different rivers.

r
# Wide format data
fish_counts_wide <- data.frame(
  river = c("Nile", "Amazon", "Yangtze"),
  day1 = c(10, 15, 8),
  day2 = c(12, 18, 9),
  day3 = c(8, 20, 10)
)

# Convert to long format
fish_counts_long <- pivot_longer(
  fish_counts_wide,
  cols = c(day1, day2, day3),
  names_to = "day",
  values_to = "catch"
)

print(fish_counts_long)

Under the Hood: pivot_longer() takes the column names you specify in cols and puts them into a new column called names_to. The values from those original columns go into a new column called values_to. It's like unstacking your data.

pivot_wider(): From Long to Wide

As you might guess, pivot_wider() does the exact opposite of pivot_longer(). It makes your dataset "wider" by increasing the number of columns and decreasing the number of rows. This is often used for creating summary tables for presentation.

Example:

Let's take our fish_counts_long data and turn it back into a wide format.

r
# Long format data (from previous example)
fish_counts_long

# Convert to wide format
fish_counts_wide_again <- pivot_wider(
  fish_counts_long,
  names_from = day,
  values_from = catch
)

print(fish_counts_wide_again)

Under the Hood: pivot_wider() takes the unique values from the column specified in names_from and turns them into new column headers. The values for these new columns are taken from the column specified in values_from.

Splitting and Combining Columns: separate() and unite() 🔗

The Problem: You have a single column that contains multiple pieces of information, or you have several columns that you'd like to combine into one.

The Solution: tidyr offers separate() and unite() to handle these situations with ease.

separate(): Splitting a Column

The separate() function takes a single character column and splits it into multiple columns.

Example:

Imagine we have a column with dates in the format "YYYY-MM-DD".

r
# Data with a combined date column
weather_data <- data.frame(
  date = c("2024-01-15", "2024-01-16", "2024-01-17"),
  temperature = c(25, 26, 24)
)

# Separate the date column
weather_data_separated <- separate(
  weather_data,
  col = date,
  into = c("year", "month", "day"),
  sep = "-"
)

print(weather_data_separated)

Under the Hood: separate() uses a separator (in this case, a hyphen) to break up the strings in the specified column and distributes the resulting pieces into the new columns you've named.

unite(): Combining Columns

The unite() function is the inverse of separate(). It combines multiple columns into a single column.

Example:

Let's take our separated weather data and put it back together.

r
# Separated data (from previous example)
weather_data_separated

# Unite the year, month, and day columns
weather_data_united <- unite(
  weather_data_separated,
  col = "full_date",
  c(year, month, day),
  sep = "/"
)

print(weather_data_united)

Under the Hood: unite() concatenates the values from the specified columns, inserting a separator between them, to create a new, single column.

Handling Missing Data: drop_na(), replace_na(), and fill() 🕵️‍♀️

The Problem: Your dataset has missing values, represented as NA in R. Missing data can cause errors in your analysis and lead to inaccurate results.

The Solution: tidyr provides a set of handy functions for dealing with missing values.

drop_na(): Removing Rows with Missing Values

The drop_na() function is a straightforward way to remove rows that contain missing values.

Example:

r
# Data with missing values
sales_data <- data.frame(
  product = c("A", "B", "C", "D"),
  sales = c(100, NA, 150, 200),
  returns = c(10, 5, NA, 12)
)

# Drop rows with any missing values
sales_data_complete <- drop_na(sales_data)

print(sales_data_complete)

You can also specify which columns to check for missing values.

r
# Drop rows with missing values only in the 'sales' column
sales_data_sales_complete <- drop_na(sales_data, sales)

print(sales_data_sales_complete)

replace_na(): Replacing Missing Values

Sometimes, you don't want to just drop missing values. The replace_na() function allows you to replace NAs with a specific value.

Example:

r
# Replace missing sales with 0 and missing returns with the mean of returns
sales_data_replaced <- replace_na(
  sales_data,
  list(sales = 0, returns = mean(sales_data$returns, na.rm = TRUE))
)

print(sales_data_replaced)

Under the Hood: replace_na() takes a list where the names are the columns and the values are what you want to replace the NAs with in those columns.

fill(): Filling Missing Values from Previous or Next Entries

The fill() function is particularly useful when you have missing values that can be inferred from the previous or next non-missing value in the same column. This is common in time-series data or when data is entered in a way that avoids repetition.

Example:

r
# Data where missing values can be filled
inventory_data <- data.frame(
  product_category = c("Fruit", NA, NA, "Vegetable", NA),
  item = c("Apple", "Banana", "Orange", "Carrot", "Broccoli")
)

# Fill missing product categories downwards
inventory_data_filled <- fill(inventory_data, product_category, .direction = "down")

print(inventory_data_filled)

You can also fill upwards by setting .direction = "up".


Further Reading and References 📚

Challenge

You are given a tibble named messy_data containing experimental results. Your task is to write a data tidying pipeline using tidyverse functions to transform it into a clean, 'tidy' format.

Requirements:

  1. First, handle the missing values in the treatment_group column by propagating the last observed non-missing value downwards.
  2. Reshape the data from its current wide format to a long format. The columns week1_results, week2_results, and week3_results should be gathered into two new columns: week and results.
  3. After reshaping, remove all rows where the results value is NA.
  4. The values in the new week column will contain a suffix (e.g., 'week1_results'). Clean this column so it only contains the week identifier (e.g., 'week1').
  5. Finally, split the results column, which contains strings like "85-125", into two new numeric columns named heart_rate and blood_pressure.

Expected result

The final output should be a tibble named tidy_data with 13 rows and 5 columns.

The columns should be:

  • subject_id (integer)
  • treatment_group (character), with no NA values.
  • week (character), containing values like 'week1', 'week2', etc.
  • heart_rate (double/numeric)
  • blood_pressure (double/numeric)

The first few rows of the resulting tibble should look like this:

apache
# A tibble: 13 × 5
   subject_id treatment_group week  heart_rate blood_pressure
        <int> <chr>           <chr>      <dbl>          <dbl>
 1          1 Control         week1         85            125
 2          1 Control         week2         82            122
 3          1 Control         week3         80            120
 4          2 Control         week1         92            130
 5          2 Control         week3         90            128
 6          3 Experimental    week1         78            118
# … with 7 more rows
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.