5

所以,我有很多 data.tables 我希望合并成一个没有重复行的 data.table。这样做的“天真”方法是用唯一的包装一个 rbind 调用:unique(do.call(rbind, list.of.tables))

这当然有效,但速度很慢。在我的实际情况中,表格有两列;哈希字符串和大小。在代码中的这一点上,它们是无键的。我首先玩过通过哈希键控,但是组合的增益被键控时间所抵消。

以下是我对这些选项进行基准测试的方法:

require(data.table)

makeHash <- function(numberOfHashes) {

  hashspace <- c(0:9, sapply(97:122, function(x) rawToChar(as.raw(x))))
  replicate(numberOfHashes, paste(sample(hashspace, 16), collapse=""))

}

mergeNoKey <- function(tableLength, modCount=tableLength/2) {

  A <- B <- data.table(hash=makeHash(tableLength), size=sample(1:(1024^2), tableLength))

  A[1:modCount] <- data.table(hash=makeHash(modCount), size=sample(1:(1024^2), modCount))

  C <- unique(rbind(A,B))
}

mergeWithKey <- function(tableLength, modCount=tableLength/2) {

  A <- B <- data.table(hash=makeHash(tableLength), size=sample(1:(1024^2), tableLength))

  A[1:modCount] <- data.table(hash=makeHash(modCount), size=sample(1:(1024^2), modCount))

  setkey(A, hash)
  setkey(B, hash)

  C <- unique(rbind(A,B))
}

require(microbenchmark)
m <- microbenchmark(mergeNoKey(1000), mergeWithKey(1000), times=10)
plot(m)

我玩过 tableLength 和 times 并没有看到性能上有很大的差异。我觉得必须有一种更 data.table 的方式来做到这一点。

在实践中,我需要对许多 data.tables 执行此操作,而不是两个,因此可伸缩性非常重要;我只是想让上面的代码保持简单。

提前致谢!

4

1 回答 1

5

我想你想使用rbindlistunique.data.table...

C <- unique( rbindlist( list( A , B ) ) )
于 2013-09-06T20:06:55.163 回答