Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R merge() Function - Merging Data Frames

R merge() Function - Merging Data Frames

R Language Examples R Language Examples

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:

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 (only keep 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 NA for those without scores)

left_join

<-

merge

(

students, scores,

by

=

"Student ID"

, all.

x

=

TRUE

)

print

(

"Left join:"

)

print

(

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 R Language Examples