13

我正在尝试使用 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 forby is required.

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

问候

4

2 回答 2

26

I think a better solution is:

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
于 2013-12-17T22:19:19.063 回答
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)]
         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

如果一个命令可以做到这一点会更好,但这相对简单。

于 2013-12-17T22:06:16.167 回答