merge()
merge joins two tables together using a column they share, like matching students to their grades by ID number. It stitches related information into one table.
In this page:
Syntax
merged <- merge(df1, df2, by = "key_column")
merge()
merge(df1, df2, by = "key") joins two data frames together based on a shared column, similar to a SQL join.
By default it performs an inner join, keeping only rows with matching keys in both frames; all = TRUE performs a full outer join instead. This is the standard way to combine related data spread across multiple tables.
Note:
Set all.x = TRUE for a left join (keep every row from the first data frame, matched or not).
Example: merge()
people <- data.frame(id = c(1, 2, 3), name = c("Alice", "Bob", "Cara"))
scores <- data.frame(id = c(1, 2), score = c(95, 82))
merged <- merge(people, scores, by = "id")
print(merged)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Merging on a column with different names in each data frame without
by.xandby.y, so R tries to use columns that do not match. - Expecting unmatched rows to be kept, when the default only keeps matches; use
all = TRUEto keep the rest. - Merging on a column with duplicate keys, which multiplies the rows.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: