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
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.
To find the unique pair combinations of an R data frame column values, we can use combn function along with unique function.
Combinations. The number of possible combinations is C(n,r)=n! r! (n−r)!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With