数据表连接中的重复col

时间:2017-03-09 22:14:41

标签: r data.table

我简单地连接2个数据包,如下所示:

set.seed(1)
DT1 <- data.table(
Idx = rep(1:100),  
x1 = round(rnorm(100,0.75,0.3),2),
x2 = round(rnorm(100,0.75,0.3),2),
x3 = round(rnorm(100,0.75,0.3),2))

DT2 <- data.table(
Idx2 = rep(1:100),
x1 = round(rep(pi,100),2),
targetcol = rep(999,100))

DT2[DT1,on = c(Idx2 = "Idx")]

这样可行,但结果中有一列i.x1,我不想要。我只想包含&#39; targetcol&#39;,因此得名。现在的问题是,在另一个例子中,我有很多这些重复的列与&#39; i&#39;在他们之前因此我想删除它们或在合并期间更好地排除它们。我知道X[Y,.(...)]应该可以做到这一点,但是我没有找到正确的方法来填充.(...)中除了一列以外的所有点,即除{{1}以外的所有列}。所以我想知道使用上面的列表语法在数据表中选择多个列的最佳方法是什么?

其次,我尝试了更新的数据表合并语法:

i.x1

但它会导致不同的列排序,命名(merge(x = DT1, y = DT2[,c("Idx2","targetcol")], by.x = "Idx",by.y = "Idx2", all.x=TRUE) x1.x),而且,我读它比其他方式慢。

解决此问题的最佳方法是什么(如果还有更多列和重复项,这只是为了说明问题)?

2 个答案:

答案 0 :(得分:2)

从HubertL代码

稍作修改的评论中删除了答案
DT1[DT2[, .(Idx2, targetcol)], on = c(Idx = "Idx2")]

答案 1 :(得分:0)

不是 data.table 解决方案,但可能仍然有意义。

对于我的包裹https://spark.apache.org/docs/latest/sql-pyspark-pandas-with-arrow.html,您有几种选择。

# devtools::install_github("moodymudskipper/safejoin")
library(safejoin)

(1)eat明确显示您想要的列:

eat(DT1, DT2, targetcol, .by = c(Idx = "Idx2"))

(2)eat列遵循您想要的模式:

eat(DT1, DT2, starts_with("target"), .by = c(Idx = "Idx2"))

(3)全部eat(或使用safe_left_join),但如有冲突,请保留第一列:

eat(DT1, DT2, .by = c(Idx = "Idx2"), .conflict = ~.x)
safe_left_join(DT1, DT2, by = c(Idx = "Idx2"), conflict = ~.x) # same thing here

它们都提供以下输出:

#   Idx   x1   x2   x3 targetcol
# 1   1 0.56 0.50 1.20       999
# 2   2 0.81 0.90 0.87       999
# 3   3 0.50 0.97 0.56       999
# 4   4 1.23 0.92 0.09       999
# 5   5 0.85 0.66 1.09       999
相关问题