How to Merge Two Data Frames in R

There are three ways to merge two data frames in R.

  1. Using the “merge()” function
  2. Using the “rbind()” function
  3. Using the “cbind()” function

Method 1: Using the “merge()” function

To merge two data frames in R, the easiest way is to use the “merge()” function. It allows you to perform different types of joins, such as inner join, left join, right join, or full join.

Example

# Create two data frames
df1 <- data.frame(
  id = c(1, 2, 3),
  name = c("Krunal", "Ankit", "Rushabh"),
  age = c(30, 28, 31)
)
df2 <- data.frame(
  id = c(1, 2, 4),
  salary = c(50000, 60000, 70000)
)

# Merge the two data frames based on the "id" column
merged_df <- merge(df1, df2, by = "id")

# View the merged data frame
merged_df

Output

  id  name   age  salary
1  1  Krunal 30   50000
2  2  Ankit  28   60000

In this code example, we used the merge() function to merge the two data frames based on the “id” column.

The resulting data frame, merged_df, contains all columns from both data frames, with rows matched based on the “id” column.

Method 2: Using the “rbind()” function

The rbind() in R is a built-in function that combines two data frames or matrices by binding them row-wise and stacking them on each other.

Example

# Create two data frames
df1 <- data.frame(
  id = c(19, 21, 46),
  salary = c(500000, 600000, 400000)
)
df2 <- data.frame(
  id = c(1, 2, 3),
  salary = c(50000, 60000, 70000)
)

# Merge the two data frames using the rbind() function
merged_df <- rbind(df1, df2)

# View the merged data frame
merged_df

Output

   id   salary
1  19   5e+05
2  21   6e+05
3  46   4e+05
4   1   5e+04
5   2   6e+04
6   3   7e+04

Method 3: Using the “cbind()” function

The cbind() function in R is used to “combine two data frames or matrices by binding them column-wise”.

Example

# Create two data frames
df1 <- data.frame(
  id = c(11, 21, 19),
  salary = c(50000, 60000, 40000)
)
df2 <- data.frame(
  gender = c("F", "M", "F"),
  name = c("Millie", "Krunal", "Khushi")
)

# Merge the two data frames using the cbind() function
merged_df <- cbind(df1, df2)

# View the merged data frame
merged_df

Output

   id   salary  gender   name
1  11   50000    F      Millie
2  21   60000    M      Krunal
3  19   40000    F      Khushi

You can see that the cbind() function merges two data frames by binding columns together.

Leave a Comment