Create all possible combinations of a data frame

Hi! You can also try this tidyverse alternative.

rows <- input %>% group_by_all() %>% group_split()
row_combinations <- t(combn(x = 1:nrow(input), m = k)) %>% as_tibble()
row_combinations %>%
  mutate_all(~ map(., ~ pluck(rows, .x))) %>% 
  unnest()

Full reprex below. I'm not sure how it performs relative to base R, but I typically prefer the most readable and/or compact option unless I'm optimizing a bottleneck. Cheers!

library(tidyverse)

input <- data.frame(stringsAsFactors = FALSE,
                    s = letters[1:6],
                    C = LETTERS[1:6])
expected_output <- tibble(s1 = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "b", "b",
                                 "b", "b", "b", "b", "c", "c", "c", "d"),
                          C1 = c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B",
                                 "B", "B", "B", "B", "C", "C", "C", "D"),
                          s2 = c("b", "b", "b", "b", "c", "c", "c", "d", "d", "e", "c", "c",
                                 "c", "d", "d", "e", "d", "d", "e", "e"),
                          C2 = c("B", "B", "B", "B", "C", "C", "C", "D", "D", "E", "C", "C",
                                 "C", "D", "D", "E", "D", "D", "E", "E"),
                          s3 = c("c", "d", "e", "f", "d", "e", "f", "e", "f", "f", "d", "e",
                                 "f", "e", "f", "f", "e", "f", "f", "f"),
                          C3 = c("C", "D", "E", "F", "D", "E", "F", "E", "F", "F", "D", "E",
                                     "F", "E", "F", "F", "E", "F", "F", "F"))
k <- 3

rows <- input %>% group_by_all() %>% group_split()
row_combinations <- t(combn(x = 1:nrow(input), m = k)) %>% as_tibble()
row_combinations %>%
  mutate_all(~ map(., ~ pluck(rows, .x))) %>% 
  unnest() %>% 
  set_names(names(expected_output)) %>% 
  all.equal(expected_output)
#> [1] TRUE

Created on 2019-03-24 by the reprex package (v0.2.1)

3 Likes