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