更快版本的组合 [英] Faster version of combn
本文介绍了更快版本的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以加快 combn
命令的速度,以从向量中获取 2 个元素的所有唯一组合?
Is there a way to speed up the combn
command to get all unique combinations of 2 elements taken from a vector?
通常会这样设置:
# Get latest version of data.table
library(devtools)
install_github("Rdatatable/data.table", build_vignettes = FALSE)
library(data.table)
# Toy data
d <- data.table(id=as.character(paste0("A", 10001:15000)))
# Transform data
system.time({
d.1 <- as.data.table(t(combn(d$id, 2)))
})
但是,combn
比使用 data.table 计算所有可能的组合慢 10 倍(23 秒对我的计算机上的 3 秒).
However, combn
is 10 times slower (23sec versus 3 sec on my computer) than calculating all possible combinations using data.table.
system.time({
d.2 <- d[, list(neighbor=d$id[-which(d$id==id)]), by=c("id")]
})
处理非常大的向量,我正在寻找一种通过仅计算唯一组合(如 combn
)来节省内存的方法,但速度与 data.table 一样(参见第二个代码片段).
Dealing with very large vectors, I am searching for a way to save memory by only calculating the unique combinations (like combn
), but with the speed of data.table (see second code snippet).
感谢您的帮助.
推荐答案
你可以使用 combnPrim
来自 <代码>gRbase
source("http://bioconductor.org/biocLite.R")
biocLite("gRbase") # will install dependent packages automatically.
system.time({
d.1 <- as.data.table(t(combn(d$id, 2)))
})
# user system elapsed
# 27.322 0.585 27.674
system.time({
d.2 <- as.data.table(t(combnPrim(d$id,2)))
})
# user system elapsed
# 2.317 0.110 2.425
identical(d.1[order(V1, V2),], d.2[order(V1,V2),])
#[1] TRUE
这篇关于更快版本的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文