如何连接(合并)数据框(内部,外部,左侧,右侧)

时间:2009-08-19 13:18:11

标签: r join merge dataframe r-faq

给出两个数据框:

df1 = data.frame(CustomerId = c(1:6), Product = c(rep("Toaster", 3), rep("Radio", 3)))
df2 = data.frame(CustomerId = c(2, 4, 6), State = c(rep("Alabama", 2), rep("Ohio", 1)))

df1
#  CustomerId Product
#           1 Toaster
#           2 Toaster
#           3 Toaster
#           4   Radio
#           5   Radio
#           6   Radio

df2
#  CustomerId   State
#           2 Alabama
#           4 Alabama
#           6    Ohio

如何进行数据库样式,即sql style, joins?也就是说,我该如何获得:

  • df1 df2df1
    仅返回左表在右表中具有匹配键的行。
  • df2 df1df2
    返回两个表中的所有行,从左侧连接记录,右表中具有匹配的键。
  • df1 df2和{{1}}的{​​{3}} 返回左表中的所有行,以及右表中具有匹配键的所有行。
  • {{1}} {{1}}和{{1}}的{​​{3}} 返回右表中的所有行,以及左表中具有匹配键的所有行。

额外信用:

如何进行SQL样式选择语句?

13 个答案:

答案 0 :(得分:1175)

使用merge函数及其可选参数:

内部联接: merge(df1, df2)适用于这些示例,因为R会自动通过公共变量名称加入帧,但您很可能希望指定{ {1}}确保您仅匹配所需的字段。如果匹配变量在不同的数据框中具有不同的名称,您还可以使用merge(df1, df2, by = "CustomerId")by.x参数。

外部加入: by.y

左外: merge(x = df1, y = df2, by = "CustomerId", all = TRUE)

右外: merge(x = df1, y = df2, by = "CustomerId", all.x = TRUE)

交叉加入: merge(x = df1, y = df2, by = "CustomerId", all.y = TRUE)

就像内部联接一样,您可能希望将“CustomerId”显式传递给R作为匹配变量。我认为最好明确说明您想要的标识符。合并;如果输入data.frames意外地改变并且稍后更容易阅读,那么它会更安全。

您可以通过向merge(x = df1, y = df2, by = NULL)提供向量来合并多个列,例如by

如果要合并的列名不相同,您可以指定,例如by = c("CustomerId", "OrderId")其中by.x = "CustomerId_in_df1", by.y = "CustomerId_in_df2"是第一个数据框中列的名称,CustomerId_in_df1是第二个数据框中列的名称。 (如果需要在多列上合并,这些也可以是向量。)

答案 1 :(得分:197)

我建议您查看Gabor Grothendieck's sqldf package,它允许您在SQL中表达这些操作。

library(sqldf)

## inner join
df3 <- sqldf("SELECT CustomerId, Product, State 
              FROM df1
              JOIN df2 USING(CustomerID)")

## left join (substitute 'right' for right join)
df4 <- sqldf("SELECT CustomerId, Product, State 
              FROM df1
              LEFT JOIN df2 USING(CustomerID)")

我发现SQL语法比它的R等价物更简单,更自然(但这可能只反映了我的RDBMS偏见)。

有关联接的详细信息,请参阅Gabor's sqldf GitHub

答案 2 :(得分:178)

内联接有 data.table 方法,这非常节省时间和内存(对于一些较大的data.frames来说也是必需的):

library(data.table)

dt1 <- data.table(df1, key = "CustomerId") 
dt2 <- data.table(df2, key = "CustomerId")

joined.dt1.dt.2 <- dt1[dt2]

merge也适用于data.tables(因为它是通用的并且调用merge.data.table

merge(dt1, dt2)
在stackoverflow上记录的

data.table:
How to do a data.table merge operation
Translating SQL joins on foreign keys to R data.table syntax
Efficient alternatives to merge for larger data.frames R
How to do a basic left outer join with data.table in R?

另一个选项是plyr包中的join功能

library(plyr)

join(df1, df2,
     type = "inner")

#   CustomerId Product   State
# 1          2 Toaster Alabama
# 2          4   Radio Alabama
# 3          6   Radio    Ohio

type的选项:innerleftrightfull

来自?join:与merge不同,无论使用何种联接类型,[join]都会保留x的顺序。

答案 3 :(得分:158)

你也可以使用Hadley Wickham令人敬畏的dplyr包进行连接。

library(dplyr)

#make sure that CustomerId cols are both type numeric
#they ARE not using the provided code in question and dplyr will complain
df1$CustomerId <- as.numeric(df1$CustomerId)
df2$CustomerId <- as.numeric(df2$CustomerId)

变异连接:使用df2

中的匹配将列添加到df1
#inner
inner_join(df1, df2)

#left outer
left_join(df1, df2)

#right outer
right_join(df1, df2)

#alternate right outer
left_join(df2, df1)

#full join
full_join(df1, df2)

过滤联接:过滤掉df1中的行,不要修改列

semi_join(df1, df2) #keep only observations in df1 that match in df2.
anti_join(df1, df2) #drops all observations in df1 that match in df2.

答案 4 :(得分:75)

R Wiki处有一些很好的例子。我会偷一对夫妇:

合并方法

由于您的密钥命名相同,因此进行内部联接的简短方法是merge():

merge(df1,df2)

可以使用“all”关键字创建完整的内部联接(来自两个表的所有记录):

merge(df1,df2, all=TRUE)

df1和df2的左外连接:

merge(df1,df2, all.x=TRUE)

df1和df2的右外连接:

merge(df1,df2, all.y=TRUE)

你可以翻转它们,拍打它们并按下它们以获得你询问的另外两个外部连接:)

下标方法

使用下标方法在左侧使用df1的左外连接将是:

df1[,"State"]<-df2[df1[ ,"Product"], "State"]

可以通过对左外连接下标示例进行mungling来创建外连接的其他组合。 (是的,我知道这相当于说“我会把它作为读者的练习......”)

答案 5 :(得分:66)

2014年的新内容:

特别是如果你对一般的数据操作感兴趣(包括排序,过滤,子集,总结等),你一定要看看dplyr,它带有各种各样的功能设计方便您专门处理数据框和某些其他数据库类型的工作。它甚至提供了相当精细的SQL接口,甚至还有一个将(大多数)SQL代码直接转换为R的功能。

dplyr包中的四个与连接相关的函数是(引用):

  • inner_join(x, y, by = NULL, copy = FALSE, ...):返回所有行 x其中y中存在匹配值,x和y中存在所有列
  • left_join(x, y, by = NULL, copy = FALSE, ...):返回x中的所有行,以及x和y中的所有列
  • semi_join(x, y, by = NULL, copy = FALSE, ...):返回x中匹配值的所有行 y,只保留x的列。
  • anti_join(x, y, by = NULL, copy = FALSE, ...):返回x中的所有行 y中没有匹配值的地方,只保留x
  • 中的列

所有here都非常详细。

可以通过select(df,"column")选择列。如果这对你来说不够SQL,那么就有sql()函数,你可以按原样输入SQL代码,它将完成你指定的操作,就像你一直在写R一样(对于更多信息,请参阅dplyr/databases vignette)。例如,如果正确应用,sql("SELECT * FROM hflights")将从“hflights”dplyr表中选择所有列(“tbl”)。

答案 6 :(得分:64)

更新data.table方法以加入数据集。有关每种类型的连接,请参阅以下示例。有两种方法,一种是从[.data.table传递第二个data.table作为第一个参数到子集,另一种方法是使用merge函数调度到快速data.table方法。

df1 = data.frame(CustomerId = c(1:6), Product = c(rep("Toaster", 3), rep("Radio", 3)))
df2 = data.frame(CustomerId = c(2L, 4L, 7L), State = c(rep("Alabama", 2), rep("Ohio", 1))) # one value changed to show full outer join

library(data.table)

dt1 = as.data.table(df1)
dt2 = as.data.table(df2)
setkey(dt1, CustomerId)
setkey(dt2, CustomerId)
# right outer join keyed data.tables
dt1[dt2]

setkey(dt1, NULL)
setkey(dt2, NULL)
# right outer join unkeyed data.tables - use `on` argument
dt1[dt2, on = "CustomerId"]

# left outer join - swap dt1 with dt2
dt2[dt1, on = "CustomerId"]

# inner join - use `nomatch` argument
dt1[dt2, nomatch=NULL, on = "CustomerId"]

# anti join - use `!` operator
dt1[!dt2, on = "CustomerId"]

# inner join - using merge method
merge(dt1, dt2, by = "CustomerId")

# full outer join
merge(dt1, dt2, by = "CustomerId", all = TRUE)

# see ?merge.data.table arguments for other cases

基准测试基础R,sqldf,dplyr和data.table 基准测试未加密/未加索引的数据集。 基准测试在50M-1行数据集上执行,在连接列上有50M-2个常用值,因此可以测试每个场景(内部,左侧,右侧,完整),并且连接仍然不容易执行。它是很好地强调连接算法的连接类型。时间安排为sqldf:0.4.11dplyr:0.7.8data.table:1.12.0

# inner
Unit: seconds
   expr       min        lq      mean    median        uq       max neval
   base 111.66266 111.66266 111.66266 111.66266 111.66266 111.66266     1
  sqldf 624.88388 624.88388 624.88388 624.88388 624.88388 624.88388     1
  dplyr  51.91233  51.91233  51.91233  51.91233  51.91233  51.91233     1
     DT  10.40552  10.40552  10.40552  10.40552  10.40552  10.40552     1
# left
Unit: seconds
   expr        min         lq       mean     median         uq        max 
   base 142.782030 142.782030 142.782030 142.782030 142.782030 142.782030     
  sqldf 613.917109 613.917109 613.917109 613.917109 613.917109 613.917109     
  dplyr  49.711912  49.711912  49.711912  49.711912  49.711912  49.711912     
     DT   9.674348   9.674348   9.674348   9.674348   9.674348   9.674348       
# right
Unit: seconds
   expr        min         lq       mean     median         uq        max
   base 122.366301 122.366301 122.366301 122.366301 122.366301 122.366301     
  sqldf 611.119157 611.119157 611.119157 611.119157 611.119157 611.119157     
  dplyr  50.384841  50.384841  50.384841  50.384841  50.384841  50.384841     
     DT   9.899145   9.899145   9.899145   9.899145   9.899145   9.899145     
# full
Unit: seconds
  expr       min        lq      mean    median        uq       max neval
  base 141.79464 141.79464 141.79464 141.79464 141.79464 141.79464     1
 dplyr  94.66436  94.66436  94.66436  94.66436  94.66436  94.66436     1
    DT  21.62573  21.62573  21.62573  21.62573  21.62573  21.62573     1

请注意,您可以使用data.table执行其他类型的联接:
   - update on join - 如果要将另一个表中的值查找到主表中    - aggregate on join - 如果您希望聚合您加入的密钥,则无需实现所有联接结果    - overlapping join - 如果你想按范围合并
   - rolling join - 如果您希望合并能够通过向前或向后滚动来匹配前一行/后一行的值    - non-equi join - 如果您的加入条件不相等

重现的代码:

library(microbenchmark)
library(sqldf)
library(dplyr)
library(data.table)
sapply(c("sqldf","dplyr","data.table"), packageVersion, simplify=FALSE)

n = 5e7
set.seed(108)
df1 = data.frame(x=sample(n,n-1L), y1=rnorm(n-1L))
df2 = data.frame(x=sample(n,n-1L), y2=rnorm(n-1L))
dt1 = as.data.table(df1)
dt2 = as.data.table(df2)

mb = list()
# inner join
microbenchmark(times = 1L,
               base = merge(df1, df2, by = "x"),
               sqldf = sqldf("SELECT * FROM df1 INNER JOIN df2 ON df1.x = df2.x"),
               dplyr = inner_join(df1, df2, by = "x"),
               DT = dt1[dt2, nomatch=NULL, on = "x"]) -> mb$inner

# left outer join
microbenchmark(times = 1L,
               base = merge(df1, df2, by = "x", all.x = TRUE),
               sqldf = sqldf("SELECT * FROM df1 LEFT OUTER JOIN df2 ON df1.x = df2.x"),
               dplyr = left_join(df1, df2, by = c("x"="x")),
               DT = dt2[dt1, on = "x"]) -> mb$left

# right outer join
microbenchmark(times = 1L,
               base = merge(df1, df2, by = "x", all.y = TRUE),
               sqldf = sqldf("SELECT * FROM df2 LEFT OUTER JOIN df1 ON df2.x = df1.x"),
               dplyr = right_join(df1, df2, by = "x"),
               DT = dt1[dt2, on = "x"]) -> mb$right

# full outer join
microbenchmark(times = 1L,
               base = merge(df1, df2, by = "x", all = TRUE),
               dplyr = full_join(df1, df2, by = "x"),
               DT = merge(dt1, dt2, by = "x", all = TRUE)) -> mb$full

lapply(mb, print) -> nul

答案 7 :(得分:24)

dplyr,因为0.4实现了所有这些连接,包括outer_join,但是值得注意的是,在0.4之前的前几个版本的它不提供outer_join,因此那里很多非常糟糕的hacky解决方法用户代码在之后漂浮了很长一段时间(你仍然可以在SO中找到这样的代码,Kaggle的答案,那个时期的github。因此这个答案仍然有用。) < / p>

加入相关release highlights

v0.5 (6/2016)

  • 处理POSIXct类型,时区,重复项,不同因素级别。更好的错误和警告。
  • 用于控制后缀重复变量名称接收的新后缀参数(#1296)

v0.4.0 (1/2015)

  • Implement right join and outer join (#96)
  • 变异连接,它将新变量从另一个表中的匹配行添加到一个表中。过滤联接,根据是否与另一个表中的观察匹配来过滤来自一个表的观察结果。

v0.3 (10/2014)

  • 现在可以通过每个表中的不同变量left_join:df1%&gt;%left_join(df2,c(“var1”=“var2”))

v0.2 (5/2014)

  • * _ join()不再重新排序列名称(#324)

v0.1.3 (4/2014)

每个hadley在该问题上的评论的解决方法:

  • right_join (x,y)就行而言与left_join(y,x)相同,只是列将是不同的顺序。使用select(new_column_order)
  • 轻松解决
  • outer_join 基本上是union(left_join(x,y),right_join(x,y)) - 即保留两个数据框中的所有行。

答案 8 :(得分:22)

在连接两个数据帧时,每个行数约为1百万行,其中一行有2列,另一行有〜20行,我惊奇地发现merge(..., all.x = TRUE, all.y = TRUE)dplyr::full_join()更快。这与dplyr v0.4

有关

合并需要大约17秒,full_join大约需要65秒。

虽然有些食物,因为我通常默认使用dplyr进行操作任务。

答案 9 :(得分:18)

对于具有0..*:0..1基数的左连接或具有0..1:0..*基数的右连接的情况,可以从连接器就地分配单边列({{1} } table)直接到joinee(0..1表),从而避免创建一个全新的数据表。这需要将来自受约人的关键列与加入者匹配,并且索引+相应地对加入者的行进行排序以进行分配。

如果密钥是单列,那么我们可以使用match()的单个调用来进行匹配。我将在这个答案中介绍这种情况。

这是一个基于OP的示例,除了我已经向0..*添加了一个id为7的额外行,以测试joiner中非匹配键的情况。这实际上是df2左连接df1

df2

在上面我硬编码了一个假设,即关键列是两个输入表的第一列。我认为,一般来说,这不是一个不合理的假设,因为,如果你有一个带有键列的data.frame,如果它还没有被设置为data.frame的第一列,那就太奇怪了。一开始。并且您可以随时重新排序列以实现它。这种假设的一个有利结果是,键列的名称不必是硬编码的,尽管我认为它只是将一个假设替换为另一个假设。 Concision是整数索引以及速度的另一个优点。在下面的基准测试中,我将更改实现以使用字符串名称索引来匹配竞争实现。

我认为这是一个特别合适的解决方案,如果你有几个表想要连接一个大表。每次合并重复重建整个表都是不必要的,而且效率低下。

另一方面,如果您因为任何原因需要通过此操作保持不变,则不能使用此解决方案,因为它直接修改了受害者。虽然在这种情况下,您只需制作副本并在副本上执行就地分配。

作为旁注,我简要介绍了多列密钥的可能匹配解决方案。不幸的是,我找到的唯一匹配解决方案是:

  • 低效的连接。例如df1 <- data.frame(CustomerId=1:6,Product=c(rep('Toaster',3L),rep('Radio',3L))); df2 <- data.frame(CustomerId=c(2L,4L,6L,7L),State=c(rep('Alabama',2L),'Ohio','Texas')); df1[names(df2)[-1L]] <- df2[match(df1[,1L],df2[,1L]),-1L]; df1; ## CustomerId Product State ## 1 1 Toaster <NA> ## 2 2 Toaster Alabama ## 3 3 Toaster <NA> ## 4 4 Radio Alabama ## 5 5 Radio <NA> ## 6 6 Radio Ohio ,或与match(interaction(df1$a,df1$b),interaction(df2$a,df2$b))相同的想法。
  • 效率低下的笛卡尔连词,例如paste()
  • 基础R outer(df1$a,df2$a,`==`) & outer(df1$b,df2$b,`==`)和等效的基于包的合并函数,它们总是分配一个新表来返回合并的结果,因此不适合基于内部分配的解决方案。

例如,请参阅Matching multiple columns on different data frames and getting other column as resultmatch two columns with two other columnsMatching on multiple columns以及我最初提出的就地解决方案Combine two data frames with different number of rows in R。 / p>

基准

我决定进行自己的基准测试,以了解就地分配方法与此问题中提供的其他解决方案的对比情况。

测试代码:

merge()

这是我之前演示的基于OP的示例的基准:

library(microbenchmark);
library(data.table);
library(sqldf);
library(plyr);
library(dplyr);

solSpecs <- list(
    merge=list(testFuncs=list(
        inner=function(df1,df2,key) merge(df1,df2,key),
        left =function(df1,df2,key) merge(df1,df2,key,all.x=T),
        right=function(df1,df2,key) merge(df1,df2,key,all.y=T),
        full =function(df1,df2,key) merge(df1,df2,key,all=T)
    )),
    data.table.unkeyed=list(argSpec='data.table.unkeyed',testFuncs=list(
        inner=function(dt1,dt2,key) dt1[dt2,on=key,nomatch=0L,allow.cartesian=T],
        left =function(dt1,dt2,key) dt2[dt1,on=key,allow.cartesian=T],
        right=function(dt1,dt2,key) dt1[dt2,on=key,allow.cartesian=T],
        full =function(dt1,dt2,key) merge(dt1,dt2,key,all=T,allow.cartesian=T) ## calls merge.data.table()
    )),
    data.table.keyed=list(argSpec='data.table.keyed',testFuncs=list(
        inner=function(dt1,dt2) dt1[dt2,nomatch=0L,allow.cartesian=T],
        left =function(dt1,dt2) dt2[dt1,allow.cartesian=T],
        right=function(dt1,dt2) dt1[dt2,allow.cartesian=T],
        full =function(dt1,dt2) merge(dt1,dt2,all=T,allow.cartesian=T) ## calls merge.data.table()
    )),
    sqldf.unindexed=list(testFuncs=list( ## note: must pass connection=NULL to avoid running against the live DB connection, which would result in collisions with the residual tables from the last query upload
        inner=function(df1,df2,key) sqldf(paste0('select * from df1 inner join df2 using(',paste(collapse=',',key),')'),connection=NULL),
        left =function(df1,df2,key) sqldf(paste0('select * from df1 left join df2 using(',paste(collapse=',',key),')'),connection=NULL),
        right=function(df1,df2,key) sqldf(paste0('select * from df2 left join df1 using(',paste(collapse=',',key),')'),connection=NULL) ## can't do right join proper, not yet supported; inverted left join is equivalent
        ##full =function(df1,df2,key) sqldf(paste0('select * from df1 full join df2 using(',paste(collapse=',',key),')'),connection=NULL) ## can't do full join proper, not yet supported; possible to hack it with a union of left joins, but too unreasonable to include in testing
    )),
    sqldf.indexed=list(testFuncs=list( ## important: requires an active DB connection with preindexed main.df1 and main.df2 ready to go; arguments are actually ignored
        inner=function(df1,df2,key) sqldf(paste0('select * from main.df1 inner join main.df2 using(',paste(collapse=',',key),')')),
        left =function(df1,df2,key) sqldf(paste0('select * from main.df1 left join main.df2 using(',paste(collapse=',',key),')')),
        right=function(df1,df2,key) sqldf(paste0('select * from main.df2 left join main.df1 using(',paste(collapse=',',key),')')) ## can't do right join proper, not yet supported; inverted left join is equivalent
        ##full =function(df1,df2,key) sqldf(paste0('select * from main.df1 full join main.df2 using(',paste(collapse=',',key),')')) ## can't do full join proper, not yet supported; possible to hack it with a union of left joins, but too unreasonable to include in testing
    )),
    plyr=list(testFuncs=list(
        inner=function(df1,df2,key) join(df1,df2,key,'inner'),
        left =function(df1,df2,key) join(df1,df2,key,'left'),
        right=function(df1,df2,key) join(df1,df2,key,'right'),
        full =function(df1,df2,key) join(df1,df2,key,'full')
    )),
    dplyr=list(testFuncs=list(
        inner=function(df1,df2,key) inner_join(df1,df2,key),
        left =function(df1,df2,key) left_join(df1,df2,key),
        right=function(df1,df2,key) right_join(df1,df2,key),
        full =function(df1,df2,key) full_join(df1,df2,key)
    )),
    in.place=list(testFuncs=list(
        left =function(df1,df2,key) { cns <- setdiff(names(df2),key); df1[cns] <- df2[match(df1[,key],df2[,key]),cns]; df1; },
        right=function(df1,df2,key) { cns <- setdiff(names(df1),key); df2[cns] <- df1[match(df2[,key],df1[,key]),cns]; df2; }
    ))
);

getSolTypes <- function() names(solSpecs);
getJoinTypes <- function() unique(unlist(lapply(solSpecs,function(x) names(x$testFuncs))));
getArgSpec <- function(argSpecs,key=NULL) if (is.null(key)) argSpecs$default else argSpecs[[key]];

initSqldf <- function() {
    sqldf(); ## creates sqlite connection on first run, cleans up and closes existing connection otherwise
    if (exists('sqldfInitFlag',envir=globalenv(),inherits=F) && sqldfInitFlag) { ## false only on first run
        sqldf(); ## creates a new connection
    } else {
        assign('sqldfInitFlag',T,envir=globalenv()); ## set to true for the one and only time
    }; ## end if
    invisible();
}; ## end initSqldf()

setUpBenchmarkCall <- function(argSpecs,joinType,solTypes=getSolTypes(),env=parent.frame()) {
    ## builds and returns a list of expressions suitable for passing to the list argument of microbenchmark(), and assigns variables to resolve symbol references in those expressions
    callExpressions <- list();
    nms <- character();
    for (solType in solTypes) {
        testFunc <- solSpecs[[solType]]$testFuncs[[joinType]];
        if (is.null(testFunc)) next; ## this join type is not defined for this solution type
        testFuncName <- paste0('tf.',solType);
        assign(testFuncName,testFunc,envir=env);
        argSpecKey <- solSpecs[[solType]]$argSpec;
        argSpec <- getArgSpec(argSpecs,argSpecKey);
        argList <- setNames(nm=names(argSpec$args),vector('list',length(argSpec$args)));
        for (i in seq_along(argSpec$args)) {
            argName <- paste0('tfa.',argSpecKey,i);
            assign(argName,argSpec$args[[i]],envir=env);
            argList[[i]] <- if (i%in%argSpec$copySpec) call('copy',as.symbol(argName)) else as.symbol(argName);
        }; ## end for
        callExpressions[[length(callExpressions)+1L]] <- do.call(call,c(list(testFuncName),argList),quote=T);
        nms[length(nms)+1L] <- solType;
    }; ## end for
    names(callExpressions) <- nms;
    callExpressions;
}; ## end setUpBenchmarkCall()

harmonize <- function(res) {
    res <- as.data.frame(res); ## coerce to data.frame
    for (ci in which(sapply(res,is.factor))) res[[ci]] <- as.character(res[[ci]]); ## coerce factor columns to character
    for (ci in which(sapply(res,is.logical))) res[[ci]] <- as.integer(res[[ci]]); ## coerce logical columns to integer (works around sqldf quirk of munging logicals to integers)
    ##for (ci in which(sapply(res,inherits,'POSIXct'))) res[[ci]] <- as.double(res[[ci]]); ## coerce POSIXct columns to double (works around sqldf quirk of losing POSIXct class) ----- POSIXct doesn't work at all in sqldf.indexed
    res <- res[order(names(res))]; ## order columns
    res <- res[do.call(order,res),]; ## order rows
    res;
}; ## end harmonize()

checkIdentical <- function(argSpecs,solTypes=getSolTypes()) {
    for (joinType in getJoinTypes()) {
        callExpressions <- setUpBenchmarkCall(argSpecs,joinType,solTypes);
        if (length(callExpressions)<2L) next;
        ex <- harmonize(eval(callExpressions[[1L]]));
        for (i in seq(2L,len=length(callExpressions)-1L)) {
            y <- harmonize(eval(callExpressions[[i]]));
            if (!isTRUE(all.equal(ex,y,check.attributes=F))) {
                ex <<- ex;
                y <<- y;
                solType <- names(callExpressions)[i];
                stop(paste0('non-identical: ',solType,' ',joinType,'.'));
            }; ## end if
        }; ## end for
    }; ## end for
    invisible();
}; ## end checkIdentical()

testJoinType <- function(argSpecs,joinType,solTypes=getSolTypes(),metric=NULL,times=100L) {
    callExpressions <- setUpBenchmarkCall(argSpecs,joinType,solTypes);
    bm <- microbenchmark(list=callExpressions,times=times);
    if (is.null(metric)) return(bm);
    bm <- summary(bm);
    res <- setNames(nm=names(callExpressions),bm[[metric]]);
    attr(res,'unit') <- attr(bm,'unit');
    res;
}; ## end testJoinType()

testAllJoinTypes <- function(argSpecs,solTypes=getSolTypes(),metric=NULL,times=100L) {
    joinTypes <- getJoinTypes();
    resList <- setNames(nm=joinTypes,lapply(joinTypes,function(joinType) testJoinType(argSpecs,joinType,solTypes,metric,times)));
    if (is.null(metric)) return(resList);
    units <- unname(unlist(lapply(resList,attr,'unit')));
    res <- do.call(data.frame,c(list(join=joinTypes),setNames(nm=solTypes,rep(list(rep(NA_real_,length(joinTypes))),length(solTypes))),list(unit=units,stringsAsFactors=F)));
    for (i in seq_along(resList)) res[i,match(names(resList[[i]]),names(res))] <- resList[[i]];
    res;
}; ## end testAllJoinTypes()

testGrid <- function(makeArgSpecsFunc,sizes,overlaps,solTypes=getSolTypes(),joinTypes=getJoinTypes(),metric='median',times=100L) {

    res <- expand.grid(size=sizes,overlap=overlaps,joinType=joinTypes,stringsAsFactors=F);
    res[solTypes] <- NA_real_;
    res$unit <- NA_character_;
    for (ri in seq_len(nrow(res))) {

        size <- res$size[ri];
        overlap <- res$overlap[ri];
        joinType <- res$joinType[ri];

        argSpecs <- makeArgSpecsFunc(size,overlap);

        checkIdentical(argSpecs,solTypes);

        cur <- testJoinType(argSpecs,joinType,solTypes,metric,times);
        res[ri,match(names(cur),names(res))] <- cur;
        res$unit[ri] <- attr(cur,'unit');

    }; ## end for

    res;

}; ## end testGrid()

这里我对随机输入数据进行基准测试,尝试不同的比例和两个输入表之间不同的键重叠模式。此基准仍限于单列整数键的情况。同样,为确保就地解决方案适用于同一表的左右连接,所有随机测试数据都使用## OP's example, supplemented with a non-matching row in df2 argSpecs <- list( default=list(copySpec=1:2,args=list( df1 <- data.frame(CustomerId=1:6,Product=c(rep('Toaster',3L),rep('Radio',3L))), df2 <- data.frame(CustomerId=c(2L,4L,6L,7L),State=c(rep('Alabama',2L),'Ohio','Texas')), 'CustomerId' )), data.table.unkeyed=list(copySpec=1:2,args=list( as.data.table(df1), as.data.table(df2), 'CustomerId' )), data.table.keyed=list(copySpec=1:2,args=list( setkey(as.data.table(df1),CustomerId), setkey(as.data.table(df2),CustomerId) )) ); ## prepare sqldf initSqldf(); sqldf('create index df1_key on df1(CustomerId);'); ## upload and create an sqlite index on df1 sqldf('create index df2_key on df2(CustomerId);'); ## upload and create an sqlite index on df2 checkIdentical(argSpecs); testAllJoinTypes(argSpecs,metric='median'); ## join merge data.table.unkeyed data.table.keyed sqldf.unindexed sqldf.indexed plyr dplyr in.place unit ## 1 inner 644.259 861.9345 923.516 9157.752 1580.390 959.2250 270.9190 NA microseconds ## 2 left 713.539 888.0205 910.045 8820.334 1529.714 968.4195 270.9185 224.3045 microseconds ## 3 right 1221.804 909.1900 923.944 8930.668 1533.135 1063.7860 269.8495 218.1035 microseconds ## 4 full 1302.203 3107.5380 3184.729 NA NA 1593.6475 270.7055 NA microseconds 基数。这是通过在生成第二个data.frame的键列时取代第一个data.frame的键列来实现的。

0..1:0..1

我写了一些代码来创建上述结果的log-log图。我为每个重叠百分比生成了一个单独的图。它有点杂乱,但我喜欢在同一个图中表示所有解决方案类型和连接类型。

我使用样条插值来显示每个解决方案/连接类型组合的平滑曲线,使用单独的pch符号绘制。连接类型由pch符号捕获,左侧和右侧的内,左,右尖括号使用点,使用完整的菱形。解决方案类型由颜色捕获,如图例所示。

makeArgSpecs.singleIntegerKey.optionalOneToOne <- function(size,overlap) {

    com <- as.integer(size*overlap);

    argSpecs <- list(
        default=list(copySpec=1:2,args=list(
            df1 <- data.frame(id=sample(size),y1=rnorm(size),y2=rnorm(size)),
            df2 <- data.frame(id=sample(c(if (com>0L) sample(df1$id,com) else integer(),seq(size+1L,len=size-com))),y3=rnorm(size),y4=rnorm(size)),
            'id'
        )),
        data.table.unkeyed=list(copySpec=1:2,args=list(
            as.data.table(df1),
            as.data.table(df2),
            'id'
        )),
        data.table.keyed=list(copySpec=1:2,args=list(
            setkey(as.data.table(df1),id),
            setkey(as.data.table(df2),id)
        ))
    );
    ## prepare sqldf
    initSqldf();
    sqldf('create index df1_key on df1(id);'); ## upload and create an sqlite index on df1
    sqldf('create index df2_key on df2(id);'); ## upload and create an sqlite index on df2

    argSpecs;

}; ## end makeArgSpecs.singleIntegerKey.optionalOneToOne()

## cross of various input sizes and key overlaps
sizes <- c(1e1L,1e3L,1e6L);
overlaps <- c(0.99,0.5,0.01);
system.time({ res <- testGrid(makeArgSpecs.singleIntegerKey.optionalOneToOne,sizes,overlaps); });
##     user   system  elapsed
## 22024.65 12308.63 34493.19

R-merge-benchmark-single-column-integer-key-optional-one-to-one-99

R-merge-benchmark-single-column-integer-key-optional-one-to-one-50

R-merge-benchmark-single-column-integer-key-optional-one-to-one-1

这是第二个大型基准,在关键列的数量和类型以及基数方面更为重要。对于此基准测试,我使用三个关键列:一个字符,一个整数和一个逻辑,对基数没有限制(即plotRes <- function(res,titleFunc,useFloor=F) { solTypes <- setdiff(names(res),c('size','overlap','joinType','unit')); ## derive from res normMult <- c(microseconds=1e-3,milliseconds=1); ## normalize to milliseconds joinTypes <- getJoinTypes(); cols <- c(merge='purple',data.table.unkeyed='blue',data.table.keyed='#00DDDD',sqldf.unindexed='brown',sqldf.indexed='orange',plyr='red',dplyr='#00BB00',in.place='magenta'); pchs <- list(inner=20L,left='<',right='>',full=23L); cexs <- c(inner=0.7,left=1,right=1,full=0.7); NP <- 60L; ord <- order(decreasing=T,colMeans(res[res$size==max(res$size),solTypes],na.rm=T)); ymajors <- data.frame(y=c(1,1e3),label=c('1ms','1s'),stringsAsFactors=F); for (overlap in unique(res$overlap)) { x1 <- res[res$overlap==overlap,]; x1[solTypes] <- x1[solTypes]*normMult[x1$unit]; x1$unit <- NULL; xlim <- c(1e1,max(x1$size)); xticks <- 10^seq(log10(xlim[1L]),log10(xlim[2L])); ylim <- c(1e-1,10^((if (useFloor) floor else ceiling)(log10(max(x1[solTypes],na.rm=T))))); ## use floor() to zoom in a little more, only sqldf.unindexed will break above, but xpd=NA will keep it visible yticks <- 10^seq(log10(ylim[1L]),log10(ylim[2L])); yticks.minor <- rep(yticks[-length(yticks)],each=9L)*1:9; plot(NA,xlim=xlim,ylim=ylim,xaxs='i',yaxs='i',axes=F,xlab='size (rows)',ylab='time (ms)',log='xy'); abline(v=xticks,col='lightgrey'); abline(h=yticks.minor,col='lightgrey',lty=3L); abline(h=yticks,col='lightgrey'); axis(1L,xticks,parse(text=sprintf('10^%d',as.integer(log10(xticks))))); axis(2L,yticks,parse(text=sprintf('10^%d',as.integer(log10(yticks)))),las=1L); axis(4L,ymajors$y,ymajors$label,las=1L,tick=F,cex.axis=0.7,hadj=0.5); for (joinType in rev(joinTypes)) { ## reverse to draw full first, since it's larger and would be more obtrusive if drawn last x2 <- x1[x1$joinType==joinType,]; for (solType in solTypes) { if (any(!is.na(x2[[solType]]))) { xy <- spline(x2$size,x2[[solType]],xout=10^(seq(log10(x2$size[1L]),log10(x2$size[nrow(x2)]),len=NP))); points(xy$x,xy$y,pch=pchs[[joinType]],col=cols[solType],cex=cexs[joinType],xpd=NA); }; ## end if }; ## end for }; ## end for ## custom legend ## due to logarithmic skew, must do all distance calcs in inches, and convert to user coords afterward ## the bottom-left corner of the legend will be defined in normalized figure coords, although we can convert to inches immediately leg.cex <- 0.7; leg.x.in <- grconvertX(0.275,'nfc','in'); leg.y.in <- grconvertY(0.6,'nfc','in'); leg.x.user <- grconvertX(leg.x.in,'in'); leg.y.user <- grconvertY(leg.y.in,'in'); leg.outpad.w.in <- 0.1; leg.outpad.h.in <- 0.1; leg.midpad.w.in <- 0.1; leg.midpad.h.in <- 0.1; leg.sol.w.in <- max(strwidth(solTypes,'in',leg.cex)); leg.sol.h.in <- max(strheight(solTypes,'in',leg.cex))*1.5; ## multiplication factor for greater line height leg.join.w.in <- max(strheight(joinTypes,'in',leg.cex))*1.5; ## ditto leg.join.h.in <- max(strwidth(joinTypes,'in',leg.cex)); leg.main.w.in <- leg.join.w.in*length(joinTypes); leg.main.h.in <- leg.sol.h.in*length(solTypes); leg.x2.user <- grconvertX(leg.x.in+leg.outpad.w.in*2+leg.main.w.in+leg.midpad.w.in+leg.sol.w.in,'in'); leg.y2.user <- grconvertY(leg.y.in+leg.outpad.h.in*2+leg.main.h.in+leg.midpad.h.in+leg.join.h.in,'in'); leg.cols.x.user <- grconvertX(leg.x.in+leg.outpad.w.in+leg.join.w.in*(0.5+seq(0L,length(joinTypes)-1L)),'in'); leg.lines.y.user <- grconvertY(leg.y.in+leg.outpad.h.in+leg.main.h.in-leg.sol.h.in*(0.5+seq(0L,length(solTypes)-1L)),'in'); leg.sol.x.user <- grconvertX(leg.x.in+leg.outpad.w.in+leg.main.w.in+leg.midpad.w.in,'in'); leg.join.y.user <- grconvertY(leg.y.in+leg.outpad.h.in+leg.main.h.in+leg.midpad.h.in,'in'); rect(leg.x.user,leg.y.user,leg.x2.user,leg.y2.user,col='white'); text(leg.sol.x.user,leg.lines.y.user,solTypes[ord],cex=leg.cex,pos=4L,offset=0); text(leg.cols.x.user,leg.join.y.user,joinTypes,cex=leg.cex,pos=4L,offset=0,srt=90); ## srt rotation applies *after* pos/offset positioning for (i in seq_along(joinTypes)) { joinType <- joinTypes[i]; points(rep(leg.cols.x.user[i],length(solTypes)),ifelse(colSums(!is.na(x1[x1$joinType==joinType,solTypes[ord]]))==0L,NA,leg.lines.y.user),pch=pchs[[joinType]],col=cols[solTypes[ord]]); }; ## end for title(titleFunc(overlap)); readline(sprintf('overlap %.02f',overlap)); }; ## end for }; ## end plotRes() titleFunc <- function(overlap) sprintf('R merge solutions: single-column integer key, 0..1:0..1 cardinality, %d%% overlap',as.integer(overlap*100)); plotRes(res,titleFunc,T); )。 (一般情况下,由于浮点比较的复杂性,不建议使用双值或复数值来定义关键列,并且基本上没有人使用原始类型,更不用说关键列了,所以我没有&#t; t在关键列中包含了这些类型。另外,为了便于说明,我最初试图通过包含POSIXct键列来使用四个关键列,但POSIXct类型与{{1}不匹配解决方案由于某种原因,可能是由于浮点比较异常,所以我删除了它。)

0..*:0..*

结果图,使用上面给出的相同绘图代码:

sqldf.indexed

R-merge-benchmark-assorted-key-optional-many-to-many-99

R-merge-benchmark-assorted-key-optional-many-to-many-50

R-merge-benchmark-assorted-key-optional-many-to-many-1

答案 10 :(得分:6)

  1. 使用merge函数,我们可以选择左表或右表的变量,就像我们熟悉SQL中的select语句一样(EX:选择a。* ...或选择b。*来自。 ....)
  2. 我们必须添加额外的代码,这些代码将从新连接的表中进行子集化。

    • SQL: - select a.* from df1 a inner join df2 b on a.CustomerId=b.CustomerId

    • R: - merge(df1, df2, by.x = "CustomerId", by.y = "CustomerId")[,names(df1)]

  3. 同样的方式

    • SQL: - select b.* from df1 a inner join df2 b on a.CustomerId=b.CustomerId

    • R: - merge(df1, df2, by.x = "CustomerId", by.y = "CustomerId")[,names(df2)]

答案 11 :(得分:6)

对于所有列的内部联接,您还可以使用 data.table -package中的fintersect dplyr 中的intersect -package作为merge的替代,而不指定by - 列。这将给出两个数据帧之间相等的行:

merge(df1, df2)
#   V1 V2
# 1  B  2
# 2  C  3
dplyr::intersect(df1, df2)
#   V1 V2
# 1  B  2
# 2  C  3
data.table::fintersect(setDT(df1), setDT(df2))
#    V1 V2
# 1:  B  2
# 2:  C  3

示例数据:

df1 <- data.frame(V1 = LETTERS[1:4], V2 = 1:4)
df2 <- data.frame(V1 = LETTERS[2:3], V2 = 2:3)

答案 12 :(得分:2)

更新联接。另一个重要的SQL样式联接是“ update join”,其中一个表中的列使用另一表进行更新(或创建)。

修改OP的示例表...

sales = data.frame(
  CustomerId = c(1, 1, 1, 3, 4, 6), 
  Year = 2000:2005,
  Product = c(rep("Toaster", 3), rep("Radio", 3))
)
cust = data.frame(
  CustomerId = c(1, 1, 4, 6), 
  Year = c(2001L, 2002L, 2002L, 2002L),
  State = state.name[1:4]
)

sales
# CustomerId Year Product
#          1 2000 Toaster
#          1 2001 Toaster
#          1 2002 Toaster
#          3 2003   Radio
#          4 2004   Radio
#          6 2005   Radio

cust
# CustomerId Year    State
#          1 2001  Alabama
#          1 2002   Alaska
#          4 2002  Arizona
#          6 2002 Arkansas

假设我们想将cust中的客户状态添加到购买表sales中,而忽略年份列。使用基数R,我们可以识别匹配的行,然后将值复制到以下位置:

sales$State <- cust$State[ match(sales$CustomerId, cust$CustomerId) ]

# CustomerId Year Product    State
#          1 2000 Toaster  Alabama
#          1 2001 Toaster  Alabama
#          1 2002 Toaster  Alabama
#          3 2003   Radio     <NA>
#          4 2004   Radio  Arizona
#          6 2005   Radio Arkansas

# cleanup for the next example
sales$State <- NULL

从这里可以看到,match从客户表中选择第一行。


更新具有多个列的联接。当我们仅联接单个列并且对第一个匹配感到满意时,上述方法效果很好。假设我们希望客户表中的测量年份与销售年份相匹配。

正如@bgoldst的答案所提到的,在这种情况下,可以选择matchinteraction。更直接地说,可以使用data.table:

library(data.table)
setDT(sales); setDT(cust)

sales[, State := cust[sales, on=.(CustomerId, Year), x.State]]

#    CustomerId Year Product   State
# 1:          1 2000 Toaster    <NA>
# 2:          1 2001 Toaster Alabama
# 3:          1 2002 Toaster  Alaska
# 4:          3 2003   Radio    <NA>
# 5:          4 2004   Radio    <NA>
# 6:          6 2005   Radio    <NA>

# cleanup for next example
sales[, State := NULL]

滚动更新加入。或者,我们可能希望采用在以下位置找到客户的最新状态:

sales[, State := cust[sales, on=.(CustomerId, Year), roll=TRUE, x.State]]

#    CustomerId Year Product    State
# 1:          1 2000 Toaster     <NA>
# 2:          1 2001 Toaster  Alabama
# 3:          1 2002 Toaster   Alaska
# 4:          3 2003   Radio     <NA>
# 5:          4 2004   Radio  Arizona
# 6:          6 2005   Radio Arkansas

以上三个示例均着重于创建/添加新列。有关更新/修改现有列的示例,请参见the related R FAQ