dplyr Tutorial

Clean, transform and summarise data with dplyr

Practical lessons on filter, mutate, group_by, joins and more — with sample data and exercises.

dplyr cheat sheet Get help with your data

dplyr Joins in R: A Complete Beginner’s Guide with Examples

Updated

Learn how to join tables in R with dplyr. This beginner-friendly guide explains every major join type with small datasets, output tables, practical data-analysis examples, common mistakes, and exercises.

What is a join in R?

A join in R combines two data frames using matching values in one or more columns. In data analysis, information is often stored across separate tables. One table might contain customer details, while another contains orders. A join lets you connect these records using a shared identifier such as customer_id.

The dplyr package provides six commonly used join functions:

  • inner_join() — keeps records with matching keys in both tables.
  • left_join() — keeps every row from the left table and adds matching columns from the right.
  • right_join() — keeps every row from the right table.
  • full_join() — keeps rows from both tables, whether or not keys match.
  • semi_join() — keeps left-table rows that have a match, without adding columns from the right.
  • anti_join() — keeps left-table rows that do not have a match.

These are called mutating joins (the first four) and filtering joins (the last two). The best join depends on which records you need to retain.

Beginner tip: In left_join(x, y), think of x as your main table. A left join is often useful for adding information to that table while retaining its rows. Review select(), filter(), and mutate() if you need to refresh basic dplyr operations.

Create two example tables

We will join a customer table to an orders table. The customer table contains one row per customer. The orders table contains one row per order, so a customer may appear more than once.

library(dplyr)

customers <- tibble(
  customer_id = c(101, 102, 103, 104),
  customer = c("Amina", "Bilal", "Sara", "Omar"),
  region = c("North", "South", "North", "West")
)

orders <- tibble(
  order_id = c(5001, 5002, 5003, 5004),
  customer_id = c(101, 101, 103, 105),
  amount = c(1200, 800, 1450, 600)
)

customers
orders
Customers table
customer_idcustomerregion
Orders table
order_idcustomer_idamount

Notice three important details:

  • Customer IDs 101 and 103 appear in both tables.
  • Customer 102 and 104 have no order in this example.
  • Order 5004 refers to customer ID 105, which is not in the customers table.

These intentional mismatches make it easier to see how each join behaves.

Understand join keys

A join key is the column—or set of columns—used to match records. In this example, customer_id is the key in both tables. When the column names are the same, you can specify it directly:

left_join(customers, orders, by = "customer_id")

The by argument tells dplyr how the two tables relate. If you omit it, dplyr may attempt to use common column names automatically, but explicitly writing by makes your intention clear and helps prevent accidental joins.

What makes a good join key?

  • It identifies the same real-world entity in both tables.
  • Its data type is compatible in both tables (for example, both character or both numeric).
  • Its values are consistently formatted, without accidental spaces or different spellings.
  • Its uniqueness matches the relationship you expect, such as one customer to many orders.

Important: A name or description is often a less reliable key than a stable ID. Two people can share a name, and the same product can have slightly different descriptions. Prefer validated identifiers whenever possible.

1. inner_join() in R: keep matching rows only

Use inner_join() when you want only records with a matching key in both data frames. In our example, customers 101 and 103 have orders and appear in both tables.

inner_join(customers, orders, by = "customer_id")

The result includes Amina’s two orders and Sara’s order. Bilal and Omar are excluded because they have no matching order; order 5004 is excluded because customer 105 is absent from the customer table.

# Keep only customers with at least one matching order
customers_with_orders <- inner_join(
  customers,
  orders,
  by = "customer_id"
)

When should you use inner_join()?

  • Analysing customers who have placed orders.
  • Combining employee records with matching payroll records.
  • Analysing products that have matching inventory information.
  • Working with observations present in both datasets.

Be careful: an inner join can silently remove unmatched records from the output. If you need to preserve every row from a primary dataset, consider left_join().

2. left_join() in R: keep all rows from the left table

left_join() is one of the most frequently used joins in R. It retains every row in the first (left) table and adds columns from the second table wherever a key matches.

customer_orders <- left_join(
  customers,
  orders,
  by = "customer_id"
)

customer_orders

Amina appears twice because she has two orders. Sara appears once. Bilal and Omar remain in the result, but their order columns contain NA. The unmatched order for customer 105 is not included because the left table is customers.

Why does left_join() sometimes create more rows?

It does not necessarily produce exactly the same number of rows as the left table. If a left-table key matches several rows in the right table, the left row is repeated once for each match. This is expected for a one-to-many relationship such as customers to orders.

Use left_join() to enrich a dataset

# Add customer region to every order that has a matching customer
orders_with_region <- left_join(
  orders,
  customers,
  by = "customer_id"
)

Here, the order table is on the left, so every order is retained, including order 5004. The region for customer 105 is NA because no matching customer record exists.

Remember: The order of arguments matters. left_join(customers, orders) preserves customer rows; left_join(orders, customers) preserves order rows.

3. right_join() and full_join() in R

right_join(): keep every row from the right table

right_join(x, y) keeps all rows from y and adds matching information from x. It is similar to reversing the table order in a left join.

right_join(customers, orders, by = "customer_id")

This preserves every order, including the order linked to customer ID 105. Since customer 105 is missing from the customers table, its customer name and region are NA.

You can often express the same requirement more naturally with left_join(orders, customers, by = "customer_id"). Both approaches retain all rows from the orders table.

full_join(): keep rows from both tables

full_join() keeps all keys from both tables. It matches records where possible and fills missing columns with NA where no match exists.

all_customer_order_records <- full_join(
  customers,
  orders,
  by = "customer_id"
)

The full join retains customers 102 and 104 even though they have no orders, and it also retains order 5004 for customer 105 even though the customer table has no such ID.

When is full_join() useful?

  • Reconciling two lists and identifying records found in only one list.
  • Comparing data from two reporting systems.
  • Combining monthly datasets when some entities appear in only one month.
  • Auditing data completeness before analysis.

4. semi_join() and anti_join() in R

Filtering joins determine which rows to keep from the left table. Unlike the first four join functions, they do not add columns from the right table.

semi_join(): keep rows that have a match

Use semi_join() when you want customer records only for IDs that appear in the orders table.

customers_with_orders <- semi_join(
  customers,
  orders,
  by = "customer_id"
)

This returns the customer rows for Amina and Sara. Each matching customer appears only once in the result, even though Amina has two orders, because semi_join() filters the left table rather than expanding it with order details.

anti_join(): find rows without a match

Use anti_join() to find customers who have no matching order:

customers_without_orders <- anti_join(
  customers,
  orders,
  by = "customer_id"
)

This returns Bilal and Omar. You can also reverse the table order to find orders that have no matching customer:

orders_without_customer <- anti_join(
  orders,
  customers,
  by = "customer_id"
)

That second result identifies order 5004, whose customer ID is 105. This is a practical data-quality check before reporting or modelling.

5. Join columns with different names

Sometimes the same key has different names in two data frames. For example, one table may use customer_id, while another uses client_id. Use a named vector in by to map the columns.

clients <- tibble(
  customer_id = c(101, 102, 103),
  customer = c("Amina", "Bilal", "Sara")
)

purchases <- tibble(
  client_id = c(101, 103, 103),
  purchase_amount = c(1200, 1450, 700)
)

left_join(
  clients,
  purchases,
  by = c("customer_id" = "client_id")
)

Read by = c("customer_id" = "client_id") as: match the customer_id column from the left data frame to the client_id column from the right data frame.

Join using multiple columns

If a single column is not sufficient to identify a match, use multiple keys. For example, sales records may be identified by both a store and a product:

left_join(
  store_sales,
  stock_levels,
  by = c("store_id", "product_id")
)

When the key names differ, map each pair explicitly:

left_join(
  sales,
  stock,
  by = c("store_id" = "branch_id", "product_id" = "item_id")
)

A match now requires both mapped key values to agree. This is useful when a product ID is repeated across stores, or when a date is part of the record identity.

6. Joining on dates and composite keys

In business datasets, keys often combine an entity and a time period. For example, a monthly performance table may contain one row per employee per month. Joining only by employee ID could match every month for that employee and multiply rows unexpectedly.

left_join(
  monthly_sales,
  monthly_targets,
  by = c("employee_id", "month")
)

Before joining, check that both tables use the same date format and period definition. One table containing a month-start date and another containing a month-end date will not match until you standardise the keys.

Join using a differently named date column

left_join(
  transactions,
  exchange_rates,
  by = c("transaction_date" = "rate_date", "currency")
)

This example matches by date and currency. It is more precise than joining on currency alone when the exchange rate changes over time.

7. Handle overlapping column names

Two tables may contain columns with the same name that are not join keys. For example, both may have a column named status. dplyr adds suffixes to distinguish these columns.

joined_data <- left_join(
  customers,
  customer_updates,
  by = "customer_id",
  suffix = c("_old", "_new")
)

The overlapping fields will use names such as status_old and status_new. Choose suffixes that explain the source or timing of each value.

For clearer output, you can also rename columns before joining with rename(). Avoid relying on automatic suffixes if the meaning of each field is important to a downstream report.

8. Duplicate keys and unexpected row counts

One of the most important concepts in joining data is key uniqueness. If the key occurs multiple times in either table, one row may match several rows. When it occurs multiple times in both tables, the output can expand substantially.

Example: one customer with multiple orders

customers <- tibble(
  customer_id = c(101, 102),
  customer = c("Amina", "Bilal")
)

orders <- tibble(
  customer_id = c(101, 101, 101, 102),
  amount = c(100, 200, 300, 150)
)

left_join(customers, orders, by = "customer_id")

Amina appears three times because there are three matching orders. This is a normal one-to-many relationship, not necessarily an error.

Many-to-many joins can multiply rows

If the left table contains two rows for a key and the right table contains three rows for that same key, the join can produce six matched combinations for that key. Before joining, decide whether that relationship is meaningful.

Check whether a key is unique:

# Find repeated customer IDs in a table
customers |>
  count(customer_id) |>
  filter(n > 1)

# Count the number of rows and distinct IDs
customers |>
  summarise(
    rows = n(),
    unique_ids = n_distinct(customer_id)
  )

If you expect one row per customer, repeated IDs need investigation. If the table represents orders, repeated customer IDs may be entirely appropriate. Do not remove duplicates automatically without understanding what each row represents.

Data integrity tip: After a join, compare the row count with what you expected. For a left join with a unique key in the right table, the result should generally retain the number of rows in the left table. If the right-side key is duplicated, the output can grow.

9. Missing and unmatched values

When a join cannot find a matching key, columns contributed by the other table are typically filled with NA. This is not the same as a zero, an empty string, or proof that the true value is absent in the real world; it means the join did not provide a value for that row.

Find unmatched records with anti_join()

# Customer IDs in orders that are not present in customers
anti_join(orders, customers, by = "customer_id")

Count missing values after a join

customer_orders |>
  summarise(
    rows = n(),
    missing_order_id = sum(is.na(order_id)),
    missing_amount = sum(is.na(amount))
  )

For data cleaning, it is often useful to investigate unmatched keys before replacing missing values. If the business rule says unmatched sales should count as zero, apply that rule explicitly and document it; do not automatically replace every NA with zero.

10. Practical dplyr join examples for data analytics

Example A: Add product names to transaction data

Transaction data may store only a product ID. A product lookup table stores the human-readable product name and category.

transactions <- tibble(
  transaction_id = c(1, 2, 3),
  product_id = c(1, 2, 1),
  quantity = c(2, 5, 1)
)

products <- tibble(
  product_id = c(1, 2, 3),
  product_name = c("Laptop", "Keyboard", "Monitor"),
  price = c(900, 40, 220)
)

transactions |>
  left_join(products, by = "product_id") |>
  mutate(line_total = quantity * price)

This adds product details to each transaction and calculates a line total. In a real analysis, confirm that each product ID appears only once in the lookup table if you expect one product record per ID.

Example B: Combine survey responses with participant details

responses_with_participants <- left_join(
  survey_responses,
  participants,
  by = "participant_id"
)

This can connect survey answers to age group, department, or other participant characteristics. Use only variables appropriate for the analysis and follow relevant privacy and data-governance requirements.

Example C: Add targets to monthly sales

sales_performance <- monthly_sales |>
  left_join(
    monthly_targets,
    by = c("employee_id", "month")
  ) |>
  mutate(
    variance = actual_sales - target_sales,
    achievement_rate = actual_sales / target_sales * 100
  )

The composite key helps ensure each employee’s sales are matched to the target for the same month. Check for zero or missing target values before interpreting the achievement rate.

Example D: Prepare analysis data for a model

model_data <- outcomes |>
  left_join(customer_features, by = "customer_id") |>
  left_join(account_summary, by = "customer_id")

This pattern is common when assembling a modelling dataset from multiple sources. Confirm that each source has the intended level of detail and that joins do not accidentally duplicate outcome rows. Also avoid including information that would not be available at the time a prediction is meant to be made.

11. Compare the six main dplyr joins

FunctionRows retainedAdds right-table columns?Typical use
inner_join(x, y)Matching keys in both tablesYesKeep records present in both sources
left_join(x, y)All rows from xYesEnrich a main dataset
right_join(x, y)All rows from yYesPreserve the right-hand dataset
full_join(x, y)All rows/keys from bothYesReconcile datasets
semi_join(x, y)Rows from x with a matchNoFilter by existence of a match
anti_join(x, y)Rows from x without a matchNoFind unmatched records

These functions are part of the dplyr data manipulation workflow. You can combine them with filter(), select(), summarise(), and the complete dplyr tutorial.

12. Common join errors and how to fix them

Error 1: Join columns are missing

Cause: The column named in by does not exist in one of the data frames, or its name is misspelled.

names(customers)
names(orders)

left_join(customers, orders, by = "customer_id")

Inspect the column names and map different names explicitly if needed.

Error 2: Key columns have incompatible types

Cause: One key is numeric while the other is character, such as 101 and "101". Convert types deliberately after checking the meaning of the values.

customers <- customers |>
  mutate(customer_id = as.character(customer_id))

orders <- orders |>
  mutate(customer_id = as.character(customer_id))

Do not convert IDs to numbers if they may contain leading zeros, letters, or other meaningful characters.

Error 3: Too many rows after the join

Cause: Duplicate keys or an unintended many-to-many relationship.

Fix: Count key frequencies in both tables, verify the intended relationship, and aggregate or deduplicate only when the business meaning justifies it.

Error 4: Unexpected NA values

Cause: The keys did not match exactly. Potential reasons include missing keys, whitespace, inconsistent formatting, different date precision, or genuinely absent records.

# Inspect records that do not match
anti_join(customers, orders, by = "customer_id")
anti_join(orders, customers, by = "customer_id")

Use these checks to investigate the unmatched rows rather than immediately discarding them.

Error 5: The wrong table was placed first

Cause: A left join preserves the first data frame, not the second.

Fix: Write down which table’s rows must all remain, and place that table first in left_join(x, y).

13. Practice exercises: dplyr joins in R

Try these exercises before opening the solutions. Use the customers and orders data frames defined near the beginning of this tutorial.

Exercise 1: Keep only matching customers and orders

Use a join to return records whose customer_id appears in both tables.

Show answer
inner_join(customers, orders, by = "customer_id")

Exercise 2: Keep every customer, even without an order

Join the orders information to the customer table without removing customers who have no order.

Show answer
left_join(customers, orders, by = "customer_id")

Exercise 3: Find customers with no matching orders

Return customers whose IDs do not occur in the orders table.

Show answer
anti_join(customers, orders, by = "customer_id")

Exercise 4: Find orders without a customer record

Identify order rows whose customer_id does not appear in customers.

Show answer
anti_join(orders, customers, by = "customer_id")

Exercise 5: Join different key names

Suppose customers uses customer_id and orders_new uses client_id. Write a left join that matches those fields.

Show answer
left_join(
  customers,
  orders_new,
  by = c("customer_id" = "client_id")
)

dplyr FAQ

What is a join in dplyr?

A join combines information from two data frames using one or more matching columns, called keys. dplyr provides inner_join(), left_join(), right_join(), full_join(), semi_join(), and anti_join() for different matching rules.

What is the difference between inner_join() and left_join() in R?

inner_join() keeps rows with matching keys in both tables. left_join() keeps every row from the left table and adds matching information from the right table; unmatched right-side values become NA.

Which dplyr join should I use most often?

left_join() is often a useful default when you want to enrich a main dataset without losing its rows. The correct join still depends on the question and whether unmatched records should be retained.

How do I join two data frames by a common column?

Use a join function and specify the shared key with by, such as left_join(customers, orders, by = "customer_id").

What if the key columns have different names?

Use a named mapping in by, such as left_join(customers, transactions, by = c("customer_id" = "client_id")). The name on the left is from the first data frame and the name on the right is from the second.

Why does a join create more rows than expected?

A join can create multiple output rows when a key occurs more than once in either table. Check key uniqueness and decide whether repeated keys represent legitimate one-to-many or many-to-many relationships.

What do semi_join() and anti_join() do?

semi_join() returns rows from the left table that have a match in the right table without adding right-table columns. anti_join() returns left-table rows that have no match in the right table.

How do I avoid duplicate column names after a join?

Use clear column names before joining, or customise suffixes with the suffix argument. Join keys with the same name are normally represented by one shared key column.

Key points to remember

  • A join combines tables by matching key columns.
  • inner_join() keeps matches; left_join() preserves all rows from the first table.
  • right_join() preserves the second table, while full_join() preserves records from both tables.
  • semi_join() and anti_join() filter the left table based on whether a match exists.
  • Use by to specify join keys, including mappings between differently named columns.
  • Repeated keys can multiply rows. Check the expected relationship and output row count.
  • Investigate unmatched records and NA values before deciding how to handle them.

Next, learn how to select rows by position with slice(). You can also practise count() and distinct(), group_by() and summarise(), and revisit the dplyr tutorial overview.