01 / 21

Joining
Data Frames in R

Learn how to combine separate data tables using left_join() and inner_join(), and understand how row counts change when you merge data.

R Programming

Why Joining Data Matters

Real-world data rarely lives in a single table. Student grades might be in one file, while student demographics sit in another. Joining lets you combine these tables by matching rows on a shared column: a key.

Key Column
The shared column used to match rows between two data frames
Combined Result
A new data frame with columns from both original tables, linked by the key

The Data Frame Refresher

A data frame in R is a table where each column is a variable and each row is an observation. Joining operates on two data frames at a time.

students id name 1 Alice 2 Bob 3 Carol 4 Dan scores id score 1 95 2 82 3 78 key: id

The dplyr Package

R's dplyr package (part of the tidyverse) provides clean, readable join functions. Before joining, always load it:

library(dplyr)
left_join()
Keep all rows from the left table, match what you can from the right
inner_join()
Keep only rows where the key matches in both tables

How left_join() Works

left_join() starts with every row in the left table and tries to find a match in the right table. If no match exists, the right-side columns are filled with NA.

students (left) id name 1 Alice 2 Bob 3 Carol 4 Dan scores (right) id score 1 95 2 82 3 78 result id name score 1 Alice 95 2 Bob 82 3 Carol 78 4 Dan NA 4 rows 3 rows 4 rows (kept all left) left_join(students, scores, by = "id")

How inner_join() Works

inner_join() keeps only the rows where the key exists in both tables. Unmatched rows from either side are dropped entirely.

students (left) id name 1 Alice 2 Bob 3 Carol 4 Dan scores (right) id score 1 95 2 82 3 78 result id name score 1 Alice 95 2 Bob 82 3 Carol 78 4 rows 3 rows 3 rows (matches only) inner_join(students, scores, by = "id")

left_join vs inner_join

Left All left rows Right left_join() Both inner_join()
left_join() inner_join()
Unmatched left rows Kept (with NA) Dropped
Result row count \(\ge\) left table rows \(\le\) left table rows
NA values possible? Yes No
Use when You need all left data You only want matches

Interpreting Row Count Changes

After a join, always check how the number of rows changed. The row count tells you a story about your data.

Rows stayed the same
Every left row found at most one match. This is a one-to-one or one-to-zero relationship.
Rows decreased
Some left rows had no match (inner_join dropped them)
Rows increased
Some left rows matched multiple right rows (one-to-many relationship)

One-to-Many Relationships

When one key value in the left table matches multiple rows in the right table, the left row is duplicated for each match. This is called a one-to-many join.

students id name 1 Alice 2 Bob test_scores id test score 1 Math 95 1 Eng 88 2 Math 72 2 Eng 80 result id name test score 1 Alice Math 95 1 Alice Eng 88 2 Bob Math 72 2 Bob Eng 80 2 rows 4 rows 4 rows! Alice appears twice: once per matching right row

Step-by-Step Join Workflow

1
Identify the key column that appears in both data frames (e.g., "id", "student_id", "code").
2
Check key types match. Use class(df$key) on both: a character key won't match a numeric key.
3
Record the row count of your left data frame: nrow(left_df).
4
Choose your join type: left_join to keep all left rows, inner_join for matches only.
5
Run the join and check nrow(result). Compare with step 3 to interpret the result.

Example 1: Simple left_join

You have a table of products and a table of prices. Not every product has a price yet.

# Create data frames products <- data.frame( item = c("apple", "banana", "cherry"), category = c("fruit", "fruit", "fruit") ) prices <- data.frame( item = c("apple", "cherry"), price = c(1.20, 3.50) ) # Join result <- left_join(products, prices, by = "item")
itemcategoryprice
applefruit1.20
bananafruitNA
cherryfruit3.50

Example 2: inner_join Filtering

Same data, but now using inner_join. Watch what happens to the banana row.

result <- inner_join(products, prices, by = "item") nrow(result) # 2 (was 3!)
itemcategoryprice
applefruit1.20
cherryfruit3.50

Example 3: Joining with Different Key Names

Sometimes the key column has a different name in each table. Use the by = c("left_name" = "right_name") syntax.

orders <- data.frame( order_id = c(101, 102, 103), customer_code = c("A", "B", "A") ) customers <- data.frame( code = c("A", "B"), name = c("Alice", "Bob") ) # Keys have different names! result <- left_join( orders, customers, by = c("customer_code" = "code") )
order_idcustomer_codename
101AAlice
102BBob
103AAlice

Using the Pipe Operator

In real R code, you will often see joins written with the pipe operator (%>% or |>), which passes the left data frame as the first argument.

# These two lines do the same thing: # Without pipe result <- left_join(students, scores, by = "id") # With pipe result <- students %>% left_join(scores, by = "id")

Common Mistakes

Mismatched key types
One table stores id as text ("1"), the other as a number (1). This can cause failed matches or warnings. Always ensure keys have the same type. Fix with mutate(id = as.character(id)).
Forgetting the "by" argument
Without by, dplyr joins on all shared column names, which may not be what you want. Always specify the key.
Unexpected row explosion
If the right table has duplicate keys, each left row multiplies. Always check nrow() after joining.

Summary Cheat Sheet

left_join() inner_join()
Syntax left_join(x, y, by) inner_join(x, y, by)
Keeps from left All rows Only matches
Keeps from right Only matches Only matches
Unmatched left rows Filled with NA Dropped
Row count change \(\ge\) left rows \(\le\) left rows
Best for Preserving all data Filtering to matches

Question 1 of 5

You have a students table with 10 rows and a grades table with 8 rows. After running left_join(students, grades, by = "id"), the result has 10 rows. What does this tell you?

Question 2 of 5

What happens to unmatched rows from the left table in an inner_join()?

Question 3 of 5

You run left_join(orders, items, by = "product_id"). The orders table has 50 rows, but the result has 65 rows. What most likely happened?

Question 4 of 5

The key in table A is character type ("1") while the key in table B is numeric (1). What is the best practice to ensure a reliable join?

Question 5 of 5

Which code correctly joins two data frames where the key is called student_id in the left table and sid in the right table?