R merge() Function - Merging Data Frames
The R merge() function is used to merge two data frames together by a common column.
merge() is similar to the JOIN operation in SQL, supporting inner join, left join, right join, and full join.
merge() function, with the following syntax:
merge(x, y, by, by.x = by, by.y = by, all = FALSE, all.x = all, all.y = all)
Parameter Description:
-
x, y The two data frames to merge.
-
by The join key (common column name).
-
all.x Whether to keep all rows of x (left join).
-
all.y Whether to keep all rows of y (right join).
-
all Whether 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
)
(
"Student table:"
)
(
students
)
(
"Score table:"
)
(
scores
)
Inner join (only keep students present in both tables)
inner_join
<-
merge
(
students, scores,
by
=
"Student ID"
)
(
"Inner join:"
)
(
inner_join
)
Left join (keep all students, fill NA for those without scores)
left_join
<-
merge
(
students, scores,
by
=
"Student ID"
, all.
x
=
TRUE
)
(
"Left join:"
)
(
left_join
)
The output of the code above is:
[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 Language Examples