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:
select(): Pick your columns.filter(): Pick your rows.arrange(): Sort your data.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.
# 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.
# 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.
# 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.
# 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.
# 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
# Find items that cost less than 50 credits
inventory |>
filter(price_credits < 50)Multiple Conditions (AND / OR)
# 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.
# 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).
# 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().
# Who is the most expensive?
inventory |>
arrange(desc(price_credits))Multi-level Sorting
You can sort by one column, then break ties with another.
# 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
PriceandQuantity, but you needTotal Revenue. - You have
Birth_Year, but you needAge. - 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
# 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.
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().
# 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.
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%).
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
- Official Documentation (The Holy Grail): dplyr.tidyverse.org
- R for Data Science (Free Book): Chapter on Data Transformation
- Cheatsheet: Data Transformation with dplyr Cheatsheet
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:
- Filter the data to include only products where the
categoryis either "Weapon" or "Gadget" AND thestock_countis greater than 0. - Mutate the data to create two new columns:
- A column named
total_value, calculated by multiplyingprice_creditsbystock_count. - A column named
price_tierusingcase_when(). The logic should be:- "Premium" if
price_creditsis greater than 1000. - "Mid-Range" if
price_creditsis greater than 200. - "Standard" for all other cases.
- "Premium" if
- A column named
- Arrange the resulting data first by
categoryin alphabetical order, and then bytotal_valuein descending order. - Select only the
product_name,category,price_tier, andtotal_valuecolumns. - Rename the
product_namecolumn toitemand thetotal_valuecolumn toinventory_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.