生成所有ID对,按组与R中的data.table [英] Generate All ID Pairs, by group with data.table in R
问题描述
我有一个data.table与许多个人(与ids)在许多组。在每个组中,我想找到每个组合的id(每对个人)。我知道如何使用拆分应用组合方法,但我希望一个data.table将更快。
I have a data.table with many individuals (with ids) in many groups. Within each group, I would like to find every combination of ids (every pair of individuals). I know how to do this with a split-apply-combine approach, but I am hoping that a data.table would be faster.
样本数据:
dat <- data.table(ids=1:20, groups=sample(x=c("A","B","C"), 20, replace=TRUE))
Split-Apply-Combine方法:
Split-Apply-Combine Method:
datS <- split(dat, f=dat$groups)
datSc <- lapply(datS, function(x){ as.data.table(t(combn(x$ids, 2)))})
rbindlist(datSc)
head(rbindlist(datSc))
V1 V2
1: 2 5
2: 2 10
3: 2 19
4: 5 10
5: 5 19
6: 10 19
我最好的data.table尝试生成一个列,而不是两个列和所有可能的组合:
My best data.table attempt produces a single column, not two columns with all the possible combinations:
dat[, combn(x=ids, m=2), by=groups]
提前感谢。
推荐答案
您需要转换 t(combn())
这是一个到
data.table
或 data.frame
的矩阵,所以这应该工作:
You need to convert the result from t(combn())
which is a matrix to a data.table
or data.frame
, so this should work:
library(data.table)
set.seed(10)
dat <- data.table(ids=1:20, groups=sample(x=c("A","B","C"), 20, replace=TRUE))
dt <- dat[, as.data.table(t(combn(ids, 2))), .(groups)]
head(dt)
groups V1 V2
1: C 1 3
2: C 1 5
3: C 1 7
4: C 1 10
5: C 1 13
6: C 1 14
这篇关于生成所有ID对,按组与R中的data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!