为什么inner_join对data.table的行为有所不同?

Mah*_*der 4 r inner-join dplyr data.table

我想使用dplyr函数将数据表与数据表连接起来inner_join().这是我的代码.

library(data.table)
library(dplyr)

DF <- data.frame(x = rep( c("a","b","c"), each=3), 
                 y = rep( c(1,3,6), 3))

DT <- data.table(x = rep( c("a","b","c"), each=3), 
                 y = rep( c(1,3,6), 3))

W <- data.frame(x = c("b","c","d"), 
              foo = c(4,2,9))
Run Code Online (Sandbox Code Playgroud)

当我尝试连接两个数据帧时,inner_join()按预期工作.

inner_join(DF,W)

Joining by: "x"
  x y foo
1 b 1   4
2 b 3   4
3 b 6   4
4 c 1   2
5 c 3   2
6 c 6   2
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将数据框与数据表连接时,inner_join()会产生意想不到的结果.

inner_join(DT,W)

Joining by: "x"
  x y foo
1 b 1   2
2 b 3   2
3 b 6   2
4 c 1   9
5 c 3   9
6 c 6   9
Run Code Online (Sandbox Code Playgroud)

有人可以给我一些提示,为什么会发生这种情况?在此先感谢您的时间.

注意:我在MAC Maverick OS X 10.9.4上使用RStudio版本0.98.1056而且sessionInfo()

R version 3.1.1 (2014-07-10)
Platform: x86_64-apple-darwin13.1.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] dplyr_0.2        data.table_1.9.2

loaded via a namespace (and not attached):
[1] assertthat_0.1 parallel_3.1.1 plyr_1.8.1     Rcpp_0.11.2    reshape2_1.4  
[6] stringr_0.6.2  tools_3.1.1   
Run Code Online (Sandbox Code Playgroud)

Aru*_*run 5

大卫提到的 因素和字符列之间的错误data.table是真的,它仍然没有修复.但不幸的是,这是一个红鲱鱼,并不是你的麻烦的来源.

但是,原因是因为没有inner_join.data.table方法dplyr v0.2,因此它调用inner_join.data.frame方法(因为a data.table也是a data.frame).

require(dplyr) ## 0.2 CRAN
require(data.table) ## 1.9.2

methods(inner_join)
# [1] inner_join.data.frame* inner_join.tbl_df*     inner_join.tbl_dt*    
# [4] inner_join.tbl_sql*  
Run Code Online (Sandbox Code Playgroud)

因此,当你这样做时:

inner_join(DF, W)
Run Code Online (Sandbox Code Playgroud)

要么

inner_join(DT, W)
Run Code Online (Sandbox Code Playgroud)

两者都调用相同的dplyr's内部联接实现.

它提供了不同的结果的原因是因为DFW两者都具有x作为因子,DT具有x作为字符列.

您可以通过更改DF$x为字符类型来重现此错误:

DF$x = as.character(DF$x)
inner_join(DF, W)
# Joining by: "x"
#   x y foo
# 1 b 1   2
# 2 b 3   2
# 3 b 6   2
# 4 c 1   9
# 5 c 3   9
# 6 c 6   9
Run Code Online (Sandbox Code Playgroud)

但这似乎已经在开发版本中修复了dplyr.