R merge() function - merge data frames

R 语言实例R Language Examples

R merge() function is used to merge two data frames together by common columns.

merge() is similar to the JOIN operation in SQL, supporting inner join, left join, right join, and full join.

The syntax of the merge() function is as follows:

merge(x, y, by, by.x = by, by.y = by, all = FALSE, all.x = all, all.y = all)

Parameter description:

  • x, yThe two data frames to be merged.

  • byJoin key (common column name).

  • all.xWhether to keep all rows in x (left join).

  • all.yWhether to keep all rows in y (right join).

  • allWhether to keep all rows (full join).

Example

# Student basic information table
students <- data.frame(
Student ID= c("S001", "S002", "S003", "S004"),
Name= c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu"),
  stringsAsFactors = FALSE
)

# Score table
scores <- data.frame(
Student ID= c("S001", "S002", "S003", "S005"),
Score= c(88, 92, 76, 80),
  stringsAsFactors = FALSE
)

print("Student table:")
print(students)
print("Score table:")
print(scores)

# Inner join (keep only students present in both tables)
inner_join <- merge(students, scores, by = Student ID)
print("Inner join:")
print(inner_join)

# Left join (keep all students, fill with NA if no score)
left_join <- merge(students, scores, by = Student ID, all.x = TRUE)
print("Left join:")
print(left_join)

Executing the above code produces the following output:

[1] "学生表:"
  学号 姓名
1 S001 张三
2 S002 李四
3 S003 王五
4 S004 赵六
[1] "成绩表:"
  学号 成绩
1 S001   88
2 S002   92
3 S003   76
4 S005   80
[1] "内连接:"
  学号 姓名 成绩
1 S001 张三   88
2 S002 李四   92
3 S003 王五   76
[1] "左连接:"
  学号 姓名 成绩
1 S001 张三   88
2 S002 李四   92
3 S003 王五   76
4 S004 赵六   NA

R 语言实例R Language Examples

Other Extensions