how can i get different combinations of words from several buckets?

I think this function solves your problem

library(combinat)
library(purrr)

allcombn <- function(...) {
  out <- combinat::permn(list(...), expand.grid, stringsAsFactors = FALSE)
  out <- vapply(out, purrr::lift_dl(paste), character(1L), sep = ".*", collapse = "|")
  paste0(out, collapse = "|")
}

Test with the following vectors

a <- c("chicken","turkey")
b <- c("legs","wings")
c <- c("x", "y", "z")

Output

> allcombn(a, b)
[1] "chicken.*legs|turkey.*legs|chicken.*wings|turkey.*wings|legs.*chicken|wings.*chicken|legs.*turkey|wings.*turkey"

> allcombn(a, b, c)
[1] "chicken.*legs.*x|turkey.*legs.*x|chicken.*wings.*x|turkey.*wings.*x|chicken.*legs.*y|turkey.*legs.*y|chicken.*wings.*y|turkey.*wings.*y|chicken.*legs.*z|turkey.*legs.*z|chicken.*wings.*z|turkey.*wings.*z|chicken.*x.*legs|turkey.*x.*legs|chicken.*y.*legs|turkey.*y.*legs|chicken.*z.*legs|turkey.*z.*legs|chicken.*x.*wings|turkey.*x.*wings|chicken.*y.*wings|turkey.*y.*wings|chicken.*z.*wings|turkey.*z.*wings|x.*chicken.*legs|y.*chicken.*legs|z.*chicken.*legs|x.*turkey.*legs|y.*turkey.*legs|z.*turkey.*legs|x.*chicken.*wings|y.*chicken.*wings|z.*chicken.*wings|x.*turkey.*wings|y.*turkey.*wings|z.*turkey.*wings|x.*legs.*chicken|y.*legs.*chicken|z.*legs.*chicken|x.*wings.*chicken|y.*wings.*chicken|z.*wings.*chicken|x.*legs.*turkey|y.*legs.*turkey|z.*legs.*turkey|x.*wings.*turkey|y.*wings.*turkey|z.*wings.*turkey|legs.*x.*chicken|wings.*x.*chicken|legs.*y.*chicken|wings.*y.*chicken|legs.*z.*chicken|wings.*z.*chicken|legs.*x.*turkey|wings.*x.*turkey|legs.*y.*turkey|wings.*y.*turkey|legs.*z.*turkey|wings.*z.*turkey|legs.*chicken.*x|wings.*chicken.*x|legs.*turkey.*x|wings.*turkey.*x|legs.*chicken.*y|wings.*chicken.*y|legs.*turkey.*y|wings.*turkey.*y|legs.*chicken.*z|wings.*chicken.*z|legs.*turkey.*z|wings.*turkey.*z"

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top