How to Combine Data Sets in R
In this article
Combining data sets in R means joining two or more data frames by common columns (like SQL joins) or stacking them by rows or columns. This is essential when you have data split across files (e.g., survey responses, sales records, customer info) and need one tidy table for analysis. Before you start, ensure R and RStudio are installed, and you have the dplyr package (install with install.packages("dplyr") if missing). You also need your data frames loaded into R, either from CSV files or created directly.
What You'll Need
- R (version 3.5 or later) and preferably RStudio.
- The
dplyrpackage for most joins and binding. - Your data sets as data frames in R (e.g.,
df1,df2). - Basic familiarity with R syntax and the pipe operator
%>%(or|>in newer R).
Step-by-Step
- Load the dplyr package
Runlibrary(dplyr). If you get an error, install it first withinstall.packages("dplyr"). - Inspect your data frames
Usestr(df1)andhead(df1)to see column names, types, and sample rows. Do the same for the second data set. Note which columns are common (e.g., an ID column) and whether row counts differ. - Decide the type of combination you need
- Join by key columns – when you have related information in separate tables (e.g., orders and customers).
- Bind rows – when you have the same columns in two tables and want to stack them (e.g., sales from different months).
- Bind columns – when you have the same number of rows and want to add columns side-by-side (e.g., two measurements on the same subjects).
- Perform a join (if combining by key)
- Inner join – keeps only rows that match in both:
inner_join(df1, df2, by = "id") - Left join – keeps all rows from df1, adds matching df2 columns:
left_join(df1, df2, by = "id") - Right join – keeps all rows from df2:
right_join(df1, df2, by = "id") - Full join – keeps all rows from both, filling NA where no match:
full_join(df1, df2, by = "id")
by = c("id1" = "id2"). - Inner join – keeps only rows that match in both:
- Bind rows (stacking)
Usebind_rows(df1, df2). Columns must match by name; missing columns become NA. This is likerbind()but more flexible. - Bind columns (side-by-side)
Usebind_cols(df1, df2). This requires the same number of rows and that row order corresponds. It does not match by key; it just pastes columns. - Assign the result to a new object
For example:combined <- left_join(df1, df2, by = "id"). Always save the output; otherwise it prints but doesn't store. - Verify the result
Check dimensions withdim(combined)and inspect withhead(combined). Confirm that the number of rows and columns make sense for your join type.
Common Mistakes
- Forgetting to load dplyr – using functions like
left_joinwithout loading the package gives an error. - Mismatched key column names – if the ID column is called
idin one andcustomer_idin the other, you must specifyby = c("id" = "customer_id"). - Not checking for duplicates – if keys are not unique, joins can multiply rows unexpectedly (cartesian product within matches).
- Using
rbind()with different column orders –rbind()requires identical column names and order, whilebind_rows()matches by name. - Using
cbind()without verifying row order – if rows are not in the same order, you'll pair the wrong records. - Overwriting original data – if you assign the result to
df1, you lose the original. Use a new name.
Tips
- Use
glimpse(combined)fromdplyrto quickly see structure. - When joining, consider using
semi_join()to filter rows in df1 that have a match in df2 without adding columns, oranti_join()to find rows without a match. - If you have multiple data frames to stack, put them in a list and use
bind_rows(list_of_dfs). - Always check for NA values after a join; they often indicate missing matches.
- For large data sets, consider using
data.tablepackage for speed, butdplyris fine for most tasks.
Troubleshooting
- Error: could not find function "left_join" – Load dplyr with
library(dplyr). - Error: "by" required – dplyr needs a
byargument for joins. If you want to join by all common columns, useby = character(0)(not recommended) or specify columns. - Result has more rows than expected – Check for duplicate keys in either data frame. Use
sum(duplicated(df1$id))to find duplicates. - bind_rows() fails because column types differ – Convert columns to the same type first, e.g.,
df1$date <- as.Date(df1$date). - bind_cols() error about row counts – Ensure both data frames have the same number of rows. If not, you need a join instead.
- After join, column names are duplicated – If both data frames have columns with the same name (other than the key), dplyr adds suffixes like
.xand.y. You can rename them before joining or usesuffix = c("_left", "_right").
Frequently Asked Questions
What is the difference between merge() and dplyr joins?
merge() is base R and similar to inner_join by default. dplyr joins are more readable and faster on large data, and they keep row order.
How do I combine data sets with different column names for the key?
Use by = c("left_key" = "right_key") in the join function. For example, left_join(df1, df2, by = c("id" = "customer_id")).
Can I combine more than two data sets at once?
Yes. For joins, you can chain: df1 %>% left_join(df2, by = "id") %>% left_join(df3, by = "id"). For row binding, put them in a list: bind_rows(list(df1, df2, df3)).
What if my data sets have different numbers of rows?
That's fine for joins – left, right, or full joins handle row differences. For bind_cols(), row counts must be equal; otherwise use a join on a key.
How do I avoid duplicate rows after a join?
Ensure your key columns are unique in at least one data frame. If duplicates exist, aggregate them first (e.g., with group_by() and summarise()) or use distinct() to remove duplicates.
Is there a way to combine data sets without writing code?
RStudio's Data pane allows you to click "Join" on two data frames in the Environment tab, but it still generates code. For reproducible work, writing code is recommended.