writer_typer
writer_typer

Reputation: 798

How to generate a list of combinations?

I have a list of string inputs that I want to iterate combinations using a function in R.

The minimum I want is three combinations and I want to generate them with replacement (they need to be used again)

What I've got now:

inputs <- c("abc", "def", "ghi", "jkl", "xyz")

The output for this is:

[1] "abc" "def" "ghi" "jkl" "xyz"

With a loop function, what I would like to get is something like this:

[1] "abc" "def" "ghi"
[2] "abc" "ghi" "xyz" 
[3] "def" "ghi" "xyz"
[4] "ghi" "xyz" "abc"
[5] "abc" "def" "ghi" "xyz"
[6] "def" "ghi" "jkl" "xyz"

# (and so on)

Upvotes: 0

Views: 66

Answers (2)

Edo
Edo

Reputation: 7858

library(purrr)
seq(3, length(inputs)) %>% map(combn, x = inputs, simplify = FALSE) %>% flatten
  • This is a solution that uses functions from tidyverse.
  • It's flexible on the length of inputs.
  • it returns a unique list at the end of combination vectors (which is similar to your expected output).

Upvotes: 2

Wimpel
Wimpel

Reputation: 27792

this should give you all 3-4-5 element combinations in a list..

lapply( 3:5, function(x) combn( inputs, x, simplify = FALSE ) )

Upvotes: 2

Related Questions