【问题标题】:Replacement for unique(rbind()) when using data.tables使用 data.tables 时替换 unique(rbind())
【发布时间】:2013-09-06 19:59:54
【问题描述】:

所以,我有很多 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 执行此操作,而不是两个,因此可伸缩性非常重要;我只是想让上面的代码保持简单。

提前致谢!

【问题讨论】:

    标签: r data.table


    【解决方案1】:

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

    C <- unique( rbindlist( list( A , B ) ) )
    

    【讨论】:

    • +1 顺便说一句,unique 在 v1.8.10(在 CRAN 上)中获得了 by 以获得更大的灵活性(感谢 Steve),并且 list() 不再复制命名输入(如本例所示) ) 在 GNU R v3.1.0(v1.8.10 知道并喜欢它)中。
    • 哇,很惊讶我错过了。我得到的收益比我希望的要少;有没有更好的办法?
    • @ClaytonJY 将rbinding 从函数中取出并测试只是 rbindrbindlist 的区别。我想您会发现大部分时间都花在了其他功能上。
    • @MatthewDowle -- 非常有趣。这是否意味着ab &lt;- list(a,b) 实际上并没有立即复制ab?或者对于何时复制 ab 以及何时不复制,是否还有其他规则?
    • @JoshO'Brien 没错,ab &lt;- list(a,b) 不会复制ab,而是增加引用计数器(已命名)。由于list 也是原始的,并且我们在data.table 中(内部和查询中)使用了很多list(),它可能会产生显着差异(尚未测试)。
    猜你喜欢
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2021-08-24
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多