How can you merge two data frames in R?

Instruction: Provide an example to illustrate how to merge two data frames by a common column in R.

Context: This question checks the candidate's ability to manipulate and combine data sets, a common task in data analysis.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

Use merge with an explicit key. Its default is an inner join; all.x=TRUE keeps every row from the left data frame.

sales <- data.frame(product_id = c(1, 1, 2, 3), amount = c(10, 20, 30, 40)) products <- data.frame(product_id = c(1, 2), name = c("A", "B")) stopifnot(!anyDuplicated(products$product_id)) result <- merge(sales, products, by = "product_id", all.x = TRUE) result <-...

Related Questions