Data Analysis
Merge
Joining Tables
merge combines rows from two data frames using a shared key column.
Program
Play the script to attach prices to orders and add the prices.
merge_join.R
Replay: real traced execution (multi-file project)
orders <- data.frame(id = c(1, 2), item = c("book", "pen"))
prices <- data.frame(item = c("book", "pen"), price = c(12, 3))
joined <- merge(orders, prices, by = "item")
total <- sum(joined$price)
cat(total, "\n", sep = "")
orders ← 2 rows x 2 cols
1orders <- data.frame(id = c(1, 2), item = c("book", "pen"))2prices <- data.frame(item = c("book", "pen"), price = c(12, 3))values this step2 rows x 2 colsordersprices ← 2 rows x 2 cols
1orders <- data.frame(id = c(1, 2), item = c("book", "pen"))2prices <- data.frame(item = c("book", "pen"), price = c(12, 3))3joined <- merge(orders, prices, by = "item")values this step2 rows x 2 colspricesjoined ← 2 rows x 3 cols
2prices <- data.frame(item = c("book", "pen"), price = c(12, 3))3joined <- merge(orders, prices, by = "item")4total <- sum(joined$price)values this step2 rows x 3 colsjoined2 rows x 2 colsorders2 rows x 2 colspricestotal ← 15
3joined <- merge(orders, prices, by = "item")4total <- sum(joined$price)5cat(total, "\n", sep = "")values this step15total12, 3joined$pricecat(total, " ", sep = "")
4total <- sum(joined$price)5cat(total, "\n", sep = "")output15values this step15total
Follow the Join
ordershas item rows(1, book)and(2, pen).priceshas price rows(book, 12)and(pen, 3).merge(..., by = "item")matches rows with the same item.- The joined rows are
(book, 1, 12)and(pen, 2, 3). - The prices add to
15, so the script prints15. | item | order id | price | included in total | | --- | --- | --- | --- | | book | 1 | 12 | yes | | pen | 2 | 3 | yes | | total | - | 15 | printed |
merge
`merge` joins data frames by matching key values.
key column
`by = "item"` names the column shared by both tables.
joined data
The joined table contains columns from both inputs.
Exercise: merge_join.R
Reproduce the output 15, then trace how book price 12 and pen price 3 join to the two orders.