Merge two data frames by common columns or row names, or do other versions of database join operations.
merge(x, y, by = intersect(names(x), names(y)),
by.x = by, by.y = by, all = FALSE, all.x = all, all.y = all,
sort = TRUE, suffixes = c(".x",".y"),
incomparables = NULL, ...)
x, y :需要合并的数据集
by, by.x, by.y :指定根据那列合并数据
all
logical; all = F 表示 all.x = F 和 all.y = F.
默认F,返回x和y中共有的行;T,返回所有行,在缺失值位置填充NA
sort :结果对by指定列排序
suffixes :suffixes = c("a","b"))代替矩阵合并后相同列的后缀x,y;
incomparables :by指定的那一列中不合并的行
name<-LETTERS[1:5]
name2<-LETTERS[3:7]
math<-sample(60:100,5)
english<-sample(60:100,5)
chemistry<-sample(60:100,5)
chinese<-sample(60:100,5)
count_1<-data.frame(name,math,english);count_1
name math english
1 A 100 75
2 B 95 81
3 C 88 71
4 D 71 61
5 E 63 95
count_2<-data.frame(name2,chemistry,chinese,math)
colnames(count_2)<-c("name","chemistry","chinese","math");count_2
name chemistry chinese math
1 C 75 62 100
2 D 96 80 95
3 E 84 89 88
4 F 76 82 71
5 G 91 97 63
inner模式:合并指定列元素交集所在的行,如果存在其它共有列,分别在列名后加上x,y加以区分
merge(count_1,count_2,by=intersect(colnames(count_1)[1],colnames(count_2)[1]))
name math.x english chemistry chinese math.y
1 C 88 71 75 62 100
2 D 71 61 96 80 95
3 E 63 95 84 89 88
# 两个矩阵有共同的列名
merge(count_1,count_2,by="name")
name math english chemistry chinese
1 C 88 71 75 62
2 D 71 61 96 80
3 E 63 95 84 89
merge(count_1,count_2,by="name",all = T)
name math.x english chemistry chinese math.y
1 A 100 75 NA NA NA
2 B 95 81 NA NA NA
3 C 88 71 75 62 100
4 D 71 61 96 80 95
5 E 63 95 84 89 88
6 F NA NA 76 82 71
7 G NA NA 91 97 63
merge(count_1,count_2,by="name",suffixes = c(".a",".b"))
name math.a english chemistry chinese math.b
1 C 88 71 75 62 100
2 D 71 61 96 80 95
3 E 63 95 84 89 88
left模式:保留指定合并列中第一个矩阵所有行
merge(count_1,count_2,by="name",all.x = T)
name math.x english chemistry chinese math.y
1 A 100 75 NA NA NA
2 B 95 81 NA NA NA
3 C 88 71 75 62 100
4 D 71 61 96 80 95
5 E 63 95 84 89 88
right模式:保留指定合并列中第二个矩阵所有行
merge(count_1,count_2,by="name",all.y = T)
name math.x english chemistry chinese math.y
1 C 88 71 75 62 100
2 D 71 61 96 80 95
3 E 63 95 84 89 88
4 F NA NA 76 82 71
5 G NA NA 91 97 63
outer模式:矩阵的行与另一个矩阵的行都一一对应输出一次
merge(count_1,count_2,by=NULL)
name.x math.x english name.y chemistry chinese math.y
1 A 100 75 C 75 62 100
2 B 95 81 C 75 62 100
3 C 88 71 C 75 62 100
4 D 71 61 C 75 62 100
5 E 63 95 C 75 62 100
6 A 100 75 D 96 80 95
7 B 95 81 D 96 80 95
8 C 88 71 D 96 80 95
9 D 71 61 D 96 80 95
10 E 63 95 D 96 80 95
11 A 100 75 E 84 89 88
12 B 95 81 E 84 89 88
13 C 88 71 E 84 89 88
14 D 71 61 E 84 89 88
15 E 63 95 E 84 89 88
16 A 100 75 F 76 82 71
17 B 95 81 F 76 82 71
18 C 88 71 F 76 82 71
19 D 71 61 F 76 82 71
20 E 63 95 F 76 82 71
21 A 100 75 G 91 97 63
22 B 95 81 G 91 97 63
23 C 88 71 G 91 97 63
24 D 71 61 G 91 97 63
25 E 63 95 G 91 97 63
网友评论