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.

Official answer available

Preview the opening of the answer, then unlock the full walkthrough.

First, let's clarify the task at hand. We're looking to merge two data frames by a common column. This is akin to performing a SQL join operation. R provides a function called merge() that accomplishes this. The basic syntax of merge() is merge(x, y, by = "common_column"), where x and y are the data frames you want to merge, and by specifies the column(s) common to both data frames that you want to merge on.

Let's assume we have two data frames: df_sales containing columns product_id and sales_amount, and df_product_info containing product_id and product_name. We want to merge these two data frames to correlate product names with sales amounts....

Related Questions