数据框中经常需要将多个表进行连接操作, 如左连接、右连接、内连接等,dplyr包也提供了数据集的连接操作,类似于 base::merge() 函数。语法如下:
内连接,合并数据仅保留匹配的记录
inner_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...)
左连接,向数据集x中加入匹配的数据集y记录
left_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...)
右连接,向数据集y中加入匹配的数据集x记录
right_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...)
全连接,合并数据保留所有记录,所有行
full_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...)
返回能够与y表匹配的x表所有记录
semi_join(x,y, by = NULL, copy = FALSE, ...)
返回无法与y表匹配的x表的所有记录
anti_join(x, y, by = NULL, copy = FALSE, ...)
by设置两个数据集用于匹配的字段名,默认使用全部同名字段进行匹配,如果两个数据集需要匹配的字段名不同,可以直接用等号指定匹配的字段名,如, by = c("a" = "b"),表示用x.a和y.b进行匹配。如果两个数据集来自不同的数据源,copy设置为TRUE时,会把数据集y的数据复制到数据集x中,出于性能上的考虑,需要谨慎设置copy参数为TRUE。合并后的数据集中同名变量,会自动添加suffix中设置的后缀加以区分。
df1 = data.frame(CustomerId=c(1:6), sex = c("f", "m", "f", "f", "m", "m"), Product=c(rep("Toaster",3), rep("Radio",3)))
df2 = data.frame(CustomerId=c(2,4,6,7),sex = c( "m", "f", "m", "f"), State=c(rep("Alabama",3), rep("Ohio",1)))
#内连接,默认使用"CustomerId"和"sex"连接
inner_join(df1, df2)
list(df1, df2) %>%purrr::reduce(inner_join)
list(df1, df2) %>%purrr::reduce(inner_join,by="sex")
#左连接,默认使用"CustomerId"和"sex"连接
left_join(df1, df2)
#右连接,默认使用"CustomerId"和"sex"连接
right_join(df1, df2)
#全连接,默认使用"CustomerId"和"sex"连接
full_join(df1, df2)
#内连接,使用"CustomerId"连接,同名字段sex会自动添加后缀
inner_join(df1, df2, by = c("CustomerId" = "CustomerId"))
#以CustomerId连接,返回df1中与df2匹配的记录
semi_join(df1, df2, by = c("CustomerId" = "CustomerId"))
#以CustomerId和sex连接,返回df1中与df2不匹配的记录
anti_join(df1, df2)
Reference
网友评论