Data Manipulation with dplyr (The Tidyverse)
8 min read
Hello there, data wrangler! π€ Welcome to the dplyr guide. So, you've got a dataset that's a bit like a wild, untamed beast. It's messy, all over the place, and frankly, a bit intimidating. Fear not! dplyr is here to be your beast-taming toolkit. It's a package in R that makes the process of cleaning, organizing, and, well, manipulating your data much more straightforward and, dare I say, enjoyable.
At its core, dplyr provides a set of "verbs" β functions that are easy to remember and use β to solve the most common data manipulation challenges. Think of it as giving you a special language to talk to your data and tell it exactly what you want it to do. No more wrestling with complicated code that looks like a secret message from an alien civilization.
Let's get this adventure started!
βοΈ Getting Started: Installation
First things first, you need to get dplyr. The easiest way is to install the entire tidyverse, a collection of R packages designed for data science that includes dplyr and plays very nicely with it.
To do this, simply run the following command in your R console:
install.packages("tidyverse")Once that's done, you'll need to load the tidyverse in your R session every time you want to use it.
library(tidyverse)Now you're all set to start manipulating data like a pro!
π Embracing the Pipe: Stringing Commands Together (%>%, |>)
Imagine you're getting ready for the day. You wake up, then you brush your teeth, then you get dressed, then you have breakfast. It's a sequence of actions. The pipe operator in R does something very similar for your data manipulation tasks.
The Problem: Without the pipe, to perform multiple operations, you'd have to either save the result of each step into a new object or nest functions within each other, which can get messy and hard to read. It's like trying to get ready for your day by putting on your shoes while you're still in bed. Just... awkward.
The Solution: The pipe operator, %>% (from the magrittr package, which is part of the tidyverse) or the native R pipe |> (available in R 4.1.0 and later), takes the output of the step before it and "pipes" it as the first argument to the function that comes after it. This allows you to chain a series of commands together in a clear, readable sequence.
Think of it as an assembly line for your data. Your raw data goes in one end, and it moves along the line, with each step performing a specific action, until the final, polished product comes out the other end.
Here's a simple example. Let's say we have a data frame of superheroes and we want to first filter for those with a certain power and then select their names.
# Let's create a pretend dataframe
superheroes <- data.frame(
name = c("Wonder Woman", "Superman", "Batman", "The Flash"),
power = c("Super strength", "Flight", "Rich", "Super speed"),
alignment = c("Good", "Good", "Good", "Good")
)
# Without the pipe
select(filter(superheroes, power == "Flight"), name)
# With the pipe
superheroes %>%
filter(power == "Flight") %>%
select(name)See how much cleaner and more intuitive the pipe version is? It reads like a story: "Take the superheroes data, then filter for those who can fly, then select their names."
π Subsetting Data: Using filter() and select()
Often, your dataset contains more information than you need for a specific analysis. It's like having a huge library and only wanting to read books by a certain author or in a specific genre. filter() and select() are your librarians, helping you find exactly what you're looking for.
The Problem: You have a large dataset and need to focus on a specific subset of rows or columns.
The Solution:
filter(): This function allows you to choose rows based on their values.select(): This function lets you pick columns by their names.
filter(): Picking Your Rows
Imagine you have a list of all the songs you've ever listened to, and you want to find only the ones by your favorite artist that you rated 5 stars. That's what filter() does.
How it works: You provide filter() with a logical condition (or multiple conditions), and it returns only the rows where that condition is true.
Example: Let's say we have data about different cars, and we only want to see the ones with more than 6 cylinders.
# Using the built-in mtcars dataset
mtcars %>%
filter(cyl > 6)You can also use multiple conditions. For instance, cars with more than 6 cylinders and more than 200 horsepower:
mtcars %>%
filter(cyl > 6 & hp > 200)The & means "and". You can also use | for "or".
select(): Choosing Your Columns
Now, imagine you have that same list of songs, but you only care about the song title and the artist, not the album, release year, or genre. select() is your tool for this.
How it works: You simply tell select() which columns you want to keep.
Example: From our car data, let's just look at the miles per gallon (mpg), number of cylinders (cyl), and horsepower (hp).
mtcars %>%
select(mpg, cyl, hp)You can also use select() to remove columns by putting a - in front of the column name. For example, to see everything except the drat and wt columns:
mtcars %>%
select(-drat, -wt)β¨ Creating and Modifying Columns with mutate()
Your data is great, but sometimes it's missing a key piece of information that you can calculate from what you already have. For instance, you might have the price and quantity of items sold, but you want to know the total revenue. mutate() is your go-to for creating new columns or changing existing ones.
The Problem: You need to add a new column that's a function of other columns, or you need to modify an existing column.
The Solution: The mutate() function adds new columns to your dataset.
How it works: You give mutate() the name of the new column you want to create and the formula for calculating it.
Example: Let's go back to our car data. What if we wanted to know the weight of the car in kilograms instead of pounds? We know that 1 pound is approximately 0.45 kilograms.
mtcars %>%
mutate(wt_kg = wt * 1000 * 0.45)Here, we created a new column called wt_kg by taking the wt column (which is in thousands of pounds) and converting it to kilograms.
A fun fact: mutate() can be a bit of a show-off. It can create multiple new columns at once!
mtcars %>%
mutate(
wt_kg = wt * 1000 * 0.45,
power_to_weight = hp / (wt * 1000)
)π Aggregation: group_by() and summarize()
Sometimes you don't need to see every single row of your data. Instead, you want to see a summary. For example, what's the average rating for each of your favorite artists? This is where group_by() and summarize() come in as a powerful duo.
The Problem: You need to calculate summary statistics for different groups within your data.
The Solution:
group_by(): This function groups your data by one or more variables.summarize(): This function collapses the data into a single row of summary statistics for each group.
Imagine you're a teacher with a class of students. You might want to know the average grade for the boys and the average grade for the girls. First, you'd group_by() gender, and then you'd summarize() to find the average grade for each group.
How it works: You first use group_by() to specify which column(s) to group your data by. Then, you use summarize() to calculate summary statistics like the mean, median, sum, etc., for each group.
Example: Let's find the average miles per gallon (mpg) for cars with different numbers of cylinders.
mtcars %>%
group_by(cyl) %>%
summarize(average_mpg = mean(mpg))This will give us a new table with two columns: cyl and average_mpg, showing the average mpg for 4, 6, and 8-cylinder cars.
You can also calculate multiple summaries at once:
mtcars %>%
group_by(cyl) %>%
summarize(
average_mpg = mean(mpg),
max_hp = max(hp)
)ποΈ Sorting and Ordering with arrange()
Once you have your data filtered, selected, and maybe even summarized, you'll often want to sort it to make it easier to understand. For example, you might want to see your top-rated songs at the top of your playlist.
The Problem: Your data is not in a meaningful order, making it hard to interpret.
The Solution: The arrange() function reorders the rows of your data frame based on the values of one or more columns.
How it works: You simply tell arrange() which column(s) you want to sort by. By default, it sorts in ascending order.
Example: Let's arrange our car data from the most to the least fuel-efficient (highest mpg to lowest). To sort in descending order, we use the desc() helper function.
mtcars %>%
arrange(desc(mpg))You can also sort by multiple columns. For instance, let's sort by the number of cylinders (ascending) and then by horsepower (descending) within each cylinder group.
mtcars %>%
arrange(cyl, desc(hp))This will show us the most powerful cars for each cylinder category first.
And there you have it! These are the fundamental verbs of dplyr that will form the backbone of your data manipulation tasks in R. By mastering these, you'll be able to tame even the wildest of datasets and get it ready for analysis and visualization. Happy wrangling! π€
π Extra Reading
Challenge
You are provided with the built-in mtcars dataset in R. Your task is to perform a series of data manipulation steps in a single, chained operation using dplyr and the pipe operator (%>%).
- Start with the
mtcarsdataset. - Filter the dataset to include only cars with 8 or fewer cylinders and horsepower (
hp) greater than 100. - Create a new column named
kpl(kilometers per liter) by convertingmpg(miles per gallon). The conversion factor is1 mpg = 0.425144 kpl. - Group the resulting data by the number of carburetors (
carb). - For each group, calculate the average
kpland the median weight (wt). Name these new summary columnsavg_kplandmedian_wtrespectively. - Arrange the final summarized data in descending order based on the
avg_kpl. - Finally, select only the
carb,avg_kpl, andmedian_wtcolumns for the output.
Expected result
The expected output is a tibble (a modern data frame) with 4 rows and 3 columns.
The columns should be named carb, avg_kpl, and median_wt.
The rows represent the summary statistics for each carb group that met the initial filtering criteria, sorted in descending order of avg_kpl.