Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all possible combinations of two columns by a variable id

Tags:

r

combinations

I need to get all permutation of 2 values given a "group id" value

I have this:

group id    value
   1         a
   1         b
   1         c
   2         b
   2         c
   2         d

and want this:

group id    value1   value2
   1         a        b
   1         a        c
   1         b        a
   1         b        c  
   1         c        a
   1         c        b
   2         b        c
   2         b        d
   2         c        b
   2         c        d
   2         d        b
   2         d        c
like image 458
João Machado Avatar asked Mar 02 '18 19:03

João Machado


People also ask

How do I get two column combinations in pandas?

By use + operator simply you can combine/merge two or multiple text/string columns in pandas DataFrame. Note that when you apply + operator on numeric columns it actually does addition instead of concatenation.

How do I find unique combinations in R?

To find the unique pair combinations of an R data frame column values, we can use combn function along with unique function.

How do you find the number of combinations in R?

Combinations. The number of possible combinations is C(n,r)=n! r! (n−r)!


1 Answers

The below is fast and simple

library(gtools)
library(data.table)

indices <- c(1,1,1,2,2,2)
variables <- c("a", "b", "c", "b", "c", "d")
dt <- data.table(indices, variables)

get_permutations <- function(df){
    perm <- permutations(nrow(unique(df[,1])), 2, df$variables)
    as.data.table(perm)
}

ds <- dt[, get_permutations(.SD), by = indices]

    indices V1 V2
 1:       1  a  b
 2:       1  a  c
 3:       1  b  a
 4:       1  b  c
 5:       1  c  a
 6:       1  c  b
 7:       2  b  c
 8:       2  b  d
 9:       2  c  b
10:       2  c  d
11:       2  d  b
12:       2  d  c
like image 62
gented Avatar answered Nov 04 '22 00:11

gented