2016-05-19 9 views
0

私は多くのグループに多くの個人(IDを持つ)を持つdata.tableを持っています。各グループ内では、すべてのIDの組み合わせ(すべての個人のペア)を検索したいと思います。私はsplit-apply-combineアプローチでこれを行う方法を知っていますが、私はdata.tableがより速くなることを望んでいます。すべてのIDペアを生成するgroup by data.table in R

サンプルデータ:

dat <- data.table(ids=1:20, groups=sample(x=c("A","B","C"), 20, replace=TRUE)) 

スプリット適用-combineメソッド:

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試みは、単一の列ではなく、すべての可能な組み合わせを持つ2つの列を作成します

dat[, combn(x=ids, m=2), by=groups] 

ありがとうございます。

答えて

3

あなたがdata.tableまたはdata.frameに行列があるt(combn())からの結果を変換する必要があるので、これは動作するはずです:

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 
1
library(data.table) 
dat <- data.table(ids=1:20, groups=sample(x=c("A","B","C"), 20, replace=TRUE)) 
ind<-unique(dat$groups) 
lapply(1:length(ind), function (i) combn(dat$ids[which(dat$groups==ind[i])],2)) 

あなたはその後、フォーマットの他のタイプのリストを変更することができます必要かもしれない。