Learn tidyverse Β· 6/13

Relational Data: Joining Tables (dplyr)

6 min read

Hello there, data wrangler! πŸ‘‹ Welcome to the world of Relational Data.

If you have ever worked with Excel, you are probably used to seeing all your data in one massive, wide sheet. But in the professional world (databases, APIs, large-scale analytics), data is messy. It is socially distant. It lives in different tables.

One table has customer info. Another has order history. A third has product details. To answer a question like "What did John Doe buy?", you need to bring these tables together.

In the tidyverse, we use the dplyr package to join these tables. It is faster than VLOOKUP and much easier to read than base R merge().

Let's load up our toolkit and get started.

r
library(tidyverse)

1. Understanding Keys: Primary and Foreign Keys πŸ”‘

Before we smash tables together, we need to know how to connect them. We connect tables using Keys.

The Problem

Imagine you have two lists. One list has names and phone numbers. The other has names and addresses. You want to combine them.

  • List A: "John Smith"
  • List B: "John Smith"

Is it the same John Smith? One might be a 20-year-old student, the other a 50-year-old baker. Matching by name is dangerous because names aren't unique.

The Solution: Keys

We use unique identifiers (IDs) to ensure we are matching the exact same entity.

1. Primary Key

A variable that uniquely identifies an observation in its own table.

  • Example: Your Social Security Number or Student ID.
  • Rule: It cannot be repeated in that table.

2. Foreign Key

A variable that references a primary key in another table.

  • Example: In an Orders table, you might have customer_id. This points back to the Customers table.
  • Rule: It can be repeated (one customer can make many orders).

πŸ›  Industry Practice

Always check if your primary key is actually unique before joining. In R, you can check this quickly:

r
# If this creates a table with counts > 1, your key is broken!
# my_table %>% count(id) %>% filter(n > 1)

2. Mutating Joins 🧬

Mutating joins add columns from one table to another, matching on the keys. They are called "mutating" because they change the structure of your dataframe (like mutate()).

Let's create some dummy data representing a band.

r
# Table 1: The Members
band_members <- tribble(
  ~name,     ~band,
  "Mick",    "Stones",
  "John",    "Beatles",
  "Paul",    "Beatles"
)

# Table 2: The Instruments
band_instruments <- tribble(
  ~name,     ~plays,
  "John",    "Guitar",
  "Paul",    "Bass",
  "Keith",   "Guitar"
)

A. left_join()

The Problem: You want to keep all your original data (left table) and attach info from another table (right table) where it exists. If there is no info, leave it blank.

The Concept: Returns all rows from the left table, and all columns from both tables. If a match is not found in the right table, it fills the new columns with NA.

Why it's the Industry Standard: This is the most common join. It prevents data loss from your primary table. You usually start with your main population (e.g., "All Active Users") and left join details to them.

r
# Join instruments TO members
band_members %>% 
  left_join(band_instruments, by = "name")

Output:

text
# A tibble: 3 Γ— 3
  name  band    plays 
  <chr> <chr>   <chr> 
1 Mick  Stones  NA     <-- Mick is in members, but not instruments. We keep him, but he gets NA.
2 John  Beatles Guitar
3 Paul  Beatles Bass  

B. inner_join()

The Problem: You only want complete records. If a person doesn't have data in both tables, you don't want to see them.

The Concept: Returns only rows where the key exists in both tables.

r
band_members %>% 
  inner_join(band_instruments, by = "name")

Output:

text
# A tibble: 2 Γ— 3
  name  band    plays 
  <chr> <chr>   <chr> 
1 John  Beatles Guitar
2 Paul  Beatles Bass  
# Mick is gone (no instrument). Keith is gone (no band).

C. right_join()

The Concept: The exact opposite of left_join. Keeps everything in the right table, drops non-matching rows from the left.

** 🧠 Pro Tip:** In the industry, we rarely use right_join. It's cognitively easier to just swap the order of your dataframes and use left_join.


3. Filtering Joins πŸ”

Sometimes you don't want to add columns. You just want to filter your rows based on whether they exist in another table.

A. semi_join()

The Problem: You have a massive table of Transactions. You have a small table of VIP_Customers. You want to see transactions only for the VIPs, but you don't need to add the VIP columns to the transaction table.

The Concept: Keeps rows in the left table that have a match in the right table. Crucially, it does not duplicate rows or add columns.

r
# Show me members who have an instrument listed
band_members %>% 
  semi_join(band_instruments, by = "name")

Output:

text
# A tibble: 2 Γ— 2
  name  band   
  <chr> <chr>  
1 John  Beatles
2 Paul  Beatles
# Mick is removed because he isn't in the instruments table.

B. anti_join()

The Problem: You are debugging. You expected every user to have a profile, but some dashboards are breaking. You need to find the users missing a profile.

The Concept: Keeps rows in the left table that do NOT have a match in the right table. This is the best tool for finding data quality issues.

r
# Show me members who do NOT have an instrument listed
band_members %>% 
  anti_join(band_instruments, by = "name")

Output:

text
# A tibble: 1 Γ— 2
  name  band  
  <chr> <chr> 
1 Mick  Stones

4. Stacking Data: Binding 🧱

Sometimes data isn't relational; it's just split up.

A. bind_rows()

The Problem: You have sales_january.csv and sales_february.csv. They have the same column names. You want one big sales_2024 dataframe.

The Concept: Stacks tables on top of each other. Columns are matched by name. If a column is missing in one table, it gets filled with NA.

r
df1 <- tibble(x = 1:2, y = c("a", "b"))
df2 <- tibble(x = 3:4, y = c("c", "d"))

bind_rows(df1, df2)

Output:

text
# A tibble: 4 Γ— 2
      x y    
  <int> <chr>
1     1 a    
2     2 b    
3     3 c    
4     4 d    

B. bind_cols()

The Problem: You have two dataframes with the exact same number of rows, sorted in the exact same order, and you want to glue them side-by-side.

The Concept: Pastes columns together.

** ⚠️ Danger Zone:** bind_cols() is risky. It relies entirely on row position. If row 5 in Table A refers to "Apple" and row 5 in Table B refers to "Banana", you just created a data error. Always prefer a Join using Keys if possible.


πŸ€“ Did you know?

In the early days of computing, joining tables was computationally expensive. Engineers would often duplicate data across files just to avoid doing joins. Today, dplyr and SQL engines optimize this so well that we almost never worry about the cost of a standard left_join.


πŸ“š Resources & References

Challenge

You are a data analyst for an e-commerce company. You have been provided with four data frames: customers, orders, products, and cancelled_orders.

Your task is to create a comprehensive report of customer activity. Write a single dplyr pipe chain that:

  1. Starts with the customers data frame.
  2. Enriches this data with information from the orders and products data frames.
  3. Ensures that all original customers are retained in the final report, regardless of whether they have placed an order.
  4. Filters out any orders that are listed in the cancelled_orders data frame.
  5. Selects only the following columns for the final report, in this exact order: customer_name, order_id, product_name, price.

Assign the final result to a variable named active_customer_report.

Expected result

The final variable active_customer_report should be a tibble (or data frame) with 4 rows and 4 columns: customer_name, order_id, product_name, and price.

  • The report must contain one row for each non-cancelled order, linked to the customer who placed it.
  • Bob's order for 'Widget B' (order_id 1002) should be excluded because it is in cancelled_orders.
  • Charlie, who has no orders, must still be present in the report. The columns order_id, product_name, and price for his row should be NA.
  • The final output should look like this:
apache
# A tibble: 4 Γ— 4
  customer_name order_id product_name price
  <chr>          <dbl> <chr>        <dbl>
1 Alice             1001 Widget A      10  
2 Alice             1004 Widget B      15.5
3 Bob               1003 Gadget A      25  
4 Charlie             NA NA            NA  
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.