笛卡尔加入data.table

时间:2013-10-18 02:46:14

标签: r data.table

我正在尝试使用data.table进行完整的笛卡尔联接,但运气不佳。

代码:


a = data.table(dt=c(20131017,20131018))
 setkey(a,dt)

 b = data.table(ticker=c("ABC","DEF","XYZ"),ind=c("MISC1","MISC2","MISC3"))
 setkey(b,ticker)

预期产出:

merge(data.frame(a),data.frame(b),all.x=TRUE,all.y=TRUE)

我已经尝试了merge(a,b,allow.cartesian=TRUE),但它给了我以下错误 - “Error in merge.data.table(a, b, allow.cartesian = TRUE) : A non-empty vector of column names for is required.

我正在使用“R version 3.0.1 (2013-05-16)”和最新的data.table个软件包。任何帮助将不胜感激!

此致

2 个答案:

答案 0 :(得分:23)

我认为更好的解决方案是:

a[,as.list(b),by=dt]

         dt ticker   ind
1: 20131017    ABC MISC1
2: 20131017    DEF MISC2
3: 20131017    XYZ MISC3
4: 20131018    ABC MISC1
5: 20131018    DEF MISC2
6: 20131018    XYZ MISC3

答案 1 :(得分:0)

扩展@Codoremifa:

> dt <- c(20131017,20131018)
> b <- data.table(ticker=c("ABC","DEF","XYZ"), ind=c("MISC1","MISC2","MISC3"), key="ticker")
> b[CJ(ticker=ticker, dt=dt)][, c(3, 1, 2), with=F]
         dt ticker   ind
1: 20131017    ABC MISC1
2: 20131018    ABC MISC1
3: 20131017    DEF MISC2
4: 20131018    DEF MISC2
5: 20131017    XYZ MISC3
6: 20131018    XYZ MISC3

如果单个命令会这样做会更好,但这是相对简单的。