Learn tidyverse · 3/13

Data Transformation Foundations (dplyr Core Verbs)

7 min read

Welcome, data explorer! 🚀

If you are reading this, you probably have a dataset that looks like a crime scene—messy, disorganized, and hiding the truth. To solve the mystery, you need tools. In the R ecosystem, specifically the tidyverse, your Swiss Army Knife is a package called dplyr.

dplyr provides a "grammar" of data manipulation. Just as English has verbs like "run", "eat", and "sleep", dplyr has verbs that tell your data what to do.

We are going to focus on the Big Four:

  1. select(): Pick your columns.
  2. filter(): Pick your rows.
  3. arrange(): Sort your data.
  4. mutate(): Make new columns.

🛠️ Prerequisite: The Setup

Before we start slicing and dicing, we need to load the library.

Standard Industry Practice:
Always load the entire tidyverse core rather than just dplyr individually. It ensures version compatibility across packages.

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

# Load the library
library(tidyverse)

The Scenario 🛒

Imagine you've been hired by "Cosmic Mart", an intergalactic convenience store. The previous manager kept records in a chaotic way. We will use this small dataset for our examples.

r
# Create our practice dataframe
inventory <- tibble(
  item_id = c(101, 102, 103, 104, 105),
  product_name = c("  Light Saber ", "Droid Oil", "Wookiee Shampoo", "Death Star Plans", "Ewok Plushie"),
  category = c("Weapon", "Maintenance", "Hygiene", "Top Secret", "Toy"),
  price_credits = c(500, 25, 15, 9999999, 12),
  stock_count = c(4, 100, 50, 1, 0),
  is_hazardous = c(TRUE, TRUE, FALSE, TRUE, FALSE)
)

print(inventory)

1. select() and rename(): Choosing and Naming Columns

The Definition

select() is used to extract specific columns from a data frame and return a new data frame with only those columns.
rename() is used to change the names of variables (columns) without dropping the others.

The Problem

Real-world datasets often have hundreds of columns. You might download a sales report that includes "Fax Number" (who uses fax?) and "Latitude_v2_backup". You don't need those to calculate profit. Also, column names like X_09_Sales_Q3_FINAL are a nightmare to type.

The Solution

Use select() to keep only what matters and rename() to make it readable.

How to use it

Basic Selection

To pick specific columns, just list them.

r
# Select only the product name and price
inventory |> 
  select(product_name, price_credits)

Note on the Pipe (|> or %>%):
You will see |> (the native pipe) or %>% (the magrittr pipe) used everywhere. It simply takes the result of the left side and passes it as the first argument to the function on the right. Think of it as saying "and then...".

Industry Tricks for select()

In production code, typing every column name is risky (what if a name changes?). dplyr offers "tidy-select" helpers.

  • starts_with("abc"): Matches names starting with "abc".
  • everything(): Selects all remaining columns (useful for reordering).
  • -column: The minus sign removes a column.
r
# Remove the ID column (we don't need it for analysis)
inventory |> 
  select(-item_id)

# Select columns that imply money or numbers
inventory |> 
  select(product_name, contains("_"))

Renaming

Sometimes you want to keep all data but fix a typo in the header.

r
# Syntax: rename(NEW_NAME = OLD_NAME)
inventory |> 
  rename(cost = price_credits)

2. filter(): Subsetting Rows Based on Logical Conditions

The Definition

filter() retains only the rows where a specified condition evaluates to TRUE.

The Problem

You have 10 million transaction records, but you only care about sales from "last Tuesday" that were "Refunds". Analyzying the whole dataset crashes your computer.

The Solution

Filter down to the subset of data you actually need.

How to use it

You use logical operators to define what stays:

  • == (Equal to)
  • != (Not equal to)
  • > or < (Greater/Less than)
  • & (AND - both must be true)
  • | (OR - at least one must be true)
  • %in% (Matches any in a list - Super useful!)

Basic Filtering

r
# Find items that cost less than 50 credits
inventory |> 
  filter(price_credits < 50)

Multiple Conditions (AND / OR)

r
# Find hazardous items that are ALSO out of stock
inventory |> 
  filter(is_hazardous == TRUE & stock_count == 0)

# Find items that are either weapons OR toys
inventory |> 
  filter(category == "Weapon" | category == "Toy")

The %in% Operator (Industry Standard)

Writing category == "A" | category == "B" | category == "C" is tedious and prone to errors. Use %in% instead.

r
# concise and clean
inventory |> 
  filter(category %in% c("Weapon", "Toy", "Hygiene"))

Fun Fact: The most common bug in data science isn't complex math—it's accidentally filtering out everything because of a typo, resulting in an empty table. If your dataframe suddenly has 0 rows, check your filter spelling! 🕵️‍♂️


3. arrange(): Sorting Your Data for Better Views

The Definition

arrange() reorders the rows of a data frame based on the values of selected columns.

The Problem

Data often comes in "insertion order" (the order it was entered). This usually looks random. If you want to find the most expensive item or the newest user, looking at random rows helps no one.

The Solution

Sort the data to bring the most extreme or relevant values to the top.

How to use it

Ascending Order (Default)

By default, arrange() sorts from smallest to largest (A-Z, 0-9).

r
# Sort items by stock count (low to high)
inventory |> 
  arrange(stock_count)

Descending Order

To see the "Top" items (highest price, most recent date), wrap the column in desc().

r
# Who is the most expensive?
inventory |> 
  arrange(desc(price_credits))

Multi-level Sorting

You can sort by one column, then break ties with another.

r
# Sort by category (A-Z), then by price (High-Low) within that category
inventory |> 
  arrange(category, desc(price_credits))

4. mutate(): Creating and Modifying Columns

The Definition

mutate() adds new variables (columns) to your data frame or modifies existing ones, preserving the existing rows.

The Problem

Raw data is rarely ready for insights.

  • You have Price and Quantity, but you need Total Revenue.
  • You have Birth_Year, but you need Age.
  • You have Product Name, but it has weird spaces at the beginning (look at " Light Saber " in our data!).

The Solution

Mutate your data to create the features you need.

How to use it

Doing Math

r
# Calculate total potential value (Price * Stock)
inventory |> 
  mutate(total_value = price_credits * stock_count)

Cleaning Text

Notice our " Light Saber " had spaces? Let's trim them.

r
inventory |> 
  mutate(product_name = str_trim(product_name))

(Note: str_trim comes from the stringr package, which is part of the tidyverse core).

Boolean Logic (The if_else standard)

In the industry, we often create "flags" or categories based on numbers. Avoid standard R if statements inside mutate; use the vectorized if_else() or case_when().

r
# Create a label for expensive items
inventory |> 
  mutate(affordability = if_else(price_credits > 100, "Luxury", "Standard"))

case_when() for complex logic

If you have more than two options (not just True/False), if_else gets messy. Enter case_when.

r
inventory |> 
  mutate(stock_status = case_when(
    stock_count == 0 ~ "Out of Stock",
    stock_count < 5  ~ "Low Stock",
    TRUE             ~ "In Stock" # 'TRUE' acts as the 'else' catch-all
  ))

🚀 Putting it All Together

In the wild, you never use just one verb. You chain them together to form a data processing pipeline.

The Mission: The Galactic Empire wants a report on hazardous items that are in stock, sorted by price (high to low), and they want a column calculating the tax (10%).

r
final_report <- inventory |> 
  # 1. Filter: Only hazardous and in stock
  filter(is_hazardous == TRUE & stock_count > 0) |> 
  
  # 2. Mutate: Calculate tax
  mutate(tax_amount = price_credits * 0.10) |> 
  
  # 3. Select: Keep only relevant columns (renaming price for clarity)
  select(product_name, category, price = price_credits, tax_amount) |> 
  
  # 4. Arrange: Most expensive first
  arrange(desc(price))

print(final_report)

Output Interpretation:
You have successfully filtered out the "Death Star Plans" (Hazardous but low stock... wait, stock was 1? Ah, logic matters!), ignored the harmless "Wookiee Shampoo", calculated the taxes, and presented a clean table.

📚 References & Extra Reading

Happy Coding! 🛸

Challenge

Challenge Instructions

You are given a tibble (a modern data frame) in R named inventory. It contains data about products sold at "Cosmic Mart" and has the following columns:

  • product_id (character)
  • product_name (character)
  • category (character: e.g., "Gadget", "Food", "Weapon", "Toy")
  • price_credits (numeric)
  • stock_count (integer)
  • supplier_id (character)

Your task is to write a single, chained dplyr pipeline to transform this data into a final report. Do not create any intermediate variables.

Your pipeline must perform the following transformations in order:

  1. Filter the data to include only products where the category is either "Weapon" or "Gadget" AND the stock_count is greater than 0.
  2. Mutate the data to create two new columns:
    • A column named total_value, calculated by multiplying price_credits by stock_count.
    • A column named price_tier using case_when(). The logic should be:
      • "Premium" if price_credits is greater than 1000.
      • "Mid-Range" if price_credits is greater than 200.
      • "Standard" for all other cases.
  3. Arrange the resulting data first by category in alphabetical order, and then by total_value in descending order.
  4. Select only the product_name, category, price_tier, and total_value columns.
  5. Rename the product_name column to item and the total_value column to inventory_worth.

Expected result

Your code should be a single, continuous dplyr pipeline starting from the inventory tibble. It must use the pipe operator (|>) to chain the following verbs in the specified order: filter(), mutate(), arrange(), select(), and rename().

The filter() function should contain a compound logical condition. The mutate() function should correctly calculate total_value and use case_when() to create the price_tier column. The arrange() function should correctly apply sorting to two columns, with one using desc(). Finally, the select() and rename() functions should produce the four specified columns with their new names.

r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.