2016-05-19 12 views
0

Ich habe eine data.table mit vielen Individuen (mit ids) in vielen Gruppen. Innerhalb jeder Gruppe möchte ich jede Kombination von IDs (jedes Paar von Individuen) finden. Ich weiß, wie man das mit einem Split-Apply-Combine-Ansatz macht, aber ich hoffe, dass eine data.table schneller wäre.Erzeuge alle ID-Paare, nach Gruppe mit data.table in R

Beispieldaten:

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

Split-Apply-Combine-Methode:

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 

Mein bester data.table Versuch erzeugt eine einzige Säule, nicht zwei Spalten mit allen möglichen Kombinationen:

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

Vielen Dank im Voraus.

Antwort

3

Sie müssen das Ergebnis von t(combn()) konvertieren, die eine Matrix zu einem data.table oder data.frame, so sollte diese Arbeit:

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)) 

Sie können dann auf jede andere Art von Format, um die Liste ändern Sie Könnte gebrauchen.