R中的merge函數(shù)類似于Excel中的Vlookup,可以實(shí)現(xiàn)對(duì)兩個(gè)數(shù)據(jù)表進(jìn)行匹配和拼接的功能。與Excel不同之處在于merge函數(shù)有4種匹配拼接模式,分別為inner,left,right和outer模式。 其中inner為默認(rèn)的匹配模式,可與sql語(yǔ)言中的join語(yǔ)句用法。
merge函數(shù)語(yǔ)法:
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, ...)
merge函數(shù)參數(shù)的說(shuō)明:
x,y 要合并的兩個(gè)數(shù)據(jù)集
by,用于連接兩個(gè)數(shù)據(jù)集的列,intersect(a,b)值向量a,b的交集,names(x)指提取數(shù)據(jù)集x的列名
by = intersect(names(x), names(y)) 是獲取數(shù)據(jù)集x,y的列名后,提取其公共列名,作為兩個(gè)數(shù)據(jù)集的連接列, 當(dāng)有多個(gè)公共列時(shí),需用下標(biāo)指出公共列,如names(x)[1],指定x數(shù)據(jù)集的第1列作為公共列
也可以直接寫為 by = ‘公共列名’ ,前提是兩個(gè)數(shù)據(jù)集中都有該列名,并且大小寫完全一致,R語(yǔ)言區(qū)分大小寫
by.x,by.y:指定依據(jù)哪些行合并數(shù)據(jù)框,默認(rèn)值為相同列名的列
all,all.x,all.y:指定x和y的行是否應(yīng)該全在輸出文件
sort:by指定的列(即公共列)是否要排序
suffixes:指定除by外相同列名的后綴
incomparables:指定by中哪些單元不進(jìn)行合并
1、讀取并創(chuàng)建數(shù)據(jù)示例
# 讀取并創(chuàng)建貸款狀態(tài)數(shù)據(jù)表
> loan_status=data.frame(read.csv('loan_status.csv',header = 1))
2、創(chuàng)建數(shù)據(jù)
> name <- c('A','B','A','A','C','D')
> school <- c('s1','s2','s1','s1','s1','s3')
> class <- c(10, 5, 4, 11, 1, 8)
> English <- c(85, 50, 90 ,90, 12, 96)
> w <- data.frame(name, school, class, English)
> w
name school class English
A s1 10 85
B s2 5 50
A s1 4 90
A s1 11 90
C s1 1 12
D s3 8 96
#同上創(chuàng)建數(shù)據(jù)集q
> name <- c('A','B','C','F')
> school <- c('s3','s2','s1','s2')
> class <- c(5, 5, 1,3)
> maths <- c(80,89,55,90)
> English <- c(88, 89, 32, 89)
> q <- data.frame(name, school, class, maths, English)
> q
name school class maths English
A s3 5 80 88
B s2 5 89 89
C s1 1 55 32
F s2 3 90 89
3、查看兩個(gè)數(shù)據(jù)表的維度
> dim(w);dim(q);
[1] 6 4
[1] 4 5
4、查看兩個(gè)數(shù)據(jù)集的列名稱
> names(w);names(q);
[1] "name""school""class""English"
[1] "name""school""class""maths""English"
# 可以看出兩個(gè)數(shù)據(jù)集有公共列
5、inner 模式匹配,只顯示兩個(gè)數(shù)據(jù)集公共列中均有的行
# 有多個(gè)公共列時(shí),需指出使用哪一列作為連接列
merge(w,q,by = intersect(names(w)[1],names(q)[1]))
# 當(dāng)兩個(gè)數(shù)據(jù)集連接列名稱同時(shí),直接用 by.x, by.y 指定連接列
merge(w,q,by.x = 'name', by.y = 'name')
# 當(dāng)兩個(gè)數(shù)據(jù)集均有連接列時(shí),直接指定連接列的名稱
merge(w,q,by = 'name')

# 連接列置于第1列; 有多個(gè)公共列,在公共列后加上x,y表示數(shù)據(jù)來(lái)源,.x表示來(lái)源于數(shù)據(jù)集w,.y表示來(lái)源于數(shù)據(jù)集q
# 數(shù)據(jù)集中w中的 name = ‘D’ 不顯示,數(shù)據(jù)集中q中的 name = ‘F’ 不顯示,只顯示公有的name行,并且用q數(shù)據(jù)集A行匹配了w數(shù)據(jù)集所有的A行
6、outer 模式,將兩張表的數(shù)據(jù)匯總,表中原來(lái)沒(méi)有的數(shù)據(jù)置為空
merge(w, q, all=TRUE, sort=TRUE)

# all = TRUE 表示選取w, q 數(shù)據(jù)集的所有行,sort = TRUE,表示按 by 列進(jìn)行排序,默認(rèn)升序
7、left 匹配模式
merge(w ,q ,all.x=TRUE,sort=TRUE) # 建議使用 指定了連接列 的情況
# 多個(gè)公共列,未指定連接列
# 左連接,設(shè)置 all.x = TRUE,結(jié)果只顯示數(shù)據(jù)w的列及w在q數(shù)據(jù)集中沒(méi)有的列

8、right 匹配模式
merge(w ,q ,by = 'name', all.y=TRUE,sort=TRUE)
# 多個(gè)公共列,指定連接列
# 左連接,設(shè)置 all.y = TRUE,結(jié)果只顯示q所有name值的記錄









暫無(wú)數(shù)據(jù)