# Finding unique combinations by row using tidyverse

Hi,
I have a data frame with hundreds of rows and 4 columns. I re-created a small sample. I'm looking to get all the unique combinations per row into a data frame of two columns as shown in df_want

``````library(tidyverse)

# data
df <- tibble(
p1 = c("A", "D"),
p2 = c("B", "E"),
p3 = c("C", "F"),
p4 = c("D", "A")
)

# unique combinations of df by row
df_want <- tibble(
player = c("A", "A", "A",
"B", "B", "C",
"D", "D", "D",
"E", "E", "F"),
partner = c("B", "C", "D",
"C", "D", "D",
"E", "F", "A",
"F", "A", "A")
)
``````

I expect there is a more elegant way to do this.

``````library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2
df <- tibble(
p1 = c("A", "D"),
p2 = c("B", "E"),
p3 = c("C", "F"),
p4 = c("D", "A")
)
df
#> # A tibble: 2 x 4
#>   p1    p2    p3    p4
#>   <chr> <chr> <chr> <chr>
#> 1 A     B     C     D
#> 2 D     E     F     A

dflong <- df |> mutate(ROW=row_number()) |>
pivot_longer(cols = -ROW) |> select(-name)
dflong
#> # A tibble: 8 x 2
#>     ROW value
#>   <int> <chr>
#> 1     1 A
#> 2     1 B
#> 3     1 C
#> 4     1 D
#> 5     2 D
#> 6     2 E
#> 7     2 F
#> 8     2 A
Nested <- dflong |> group_by(ROW) |>  nest()

CombFunc <- function(DF) {
tmp <- combn(DF\$value,2)
tmp <- t(tmp)
tmp <- as.data.frame(tmp)
colnames(tmp) <- c("player","partner")
return(tmp)
}

Combin <- mutate(Nested, Comb= lapply(data, CombFunc))
UNNESTED <- unnest(Combin,cols = Comb) |> ungroup()
df_wanted <- select(UNNESTED, player,partner)
df_wanted
#> # A tibble: 12 x 2
#>    player partner
#>    <chr>  <chr>
#>  1 A      B
#>  2 A      C
#>  3 A      D
#>  4 B      C
#>  5 B      D
#>  6 C      D
#>  7 D      E
#>  8 D      F
#>  9 D      A
#> 10 E      F
#> 11 E      A
#> 12 F      A
``````

Created on 2022-02-22 by the reprex package (v2.0.1)

Thank you. Appreciate the support.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.