combinations within groups in R

235 Views Asked by At

I have the following DataFrame in R:

df = data.frame(id = c(1,1,1,2,2),
                year = c(2000, 2000, 2000, 2001, 2001),             
                name= c("A", "B", "C", "D", "E"))  

I need to create an edge-list for network analysis. For each id, I want all the possible combinations (without repetition) of the values in name.

Here below is the desired output:

df = data.frame(id = c(1,1,1,2),
                year = c(2000, 2000, 2000, 2001),             
                name1= c("A", "A", "B", "D"),
                name2= c("B", "C", "C", "E"))  
1

There are 1 best solutions below

4
On

Try the following data.table option using combn

> library(data.table)
> setDT(df)[, as.data.table(t(combn(name, 2))), .(id, year)]
   id year V1 V2
1:  1 2000  A  B
2:  1 2000  A  C
3:  1 2000  B  C
4:  2 2001  D  E