Giuseppe Petri
Giuseppe Petri

Reputation: 640

Get all the combinations of a given set of elements with permutation in r

I have two parameters (say "A" and "B"), that need to be tested against a set of treatments ("PD", "MO", "K") applied alone or in combination, in addition to not having any treatment ("."). I need to get all the possible combinations of treatments affecting parameters "A" and "B". I came with a very rudimentary way to do it, but I need a more efficient way to do it because a have a large list of treatments.

This is my reproducible example

effects <- c(".", "PD", "MO", "PD,MO", "K", "K,PD", "K,MO", "K,PD,MO")

res.perm <- permutations(n = 8, r = 2, v = effects, repeats.allowed = TRUE)
print(res.perm, quote = FALSE)

An this is what I get

enter image description here

.....

enter image description here

If someone could provide a more elegant or smart way to do it, it would be great. The input I actually need to use is V1 = c("PD", "MO", "K")

Thanks.

Upvotes: 1

Views: 176

Answers (1)

akrun
akrun

Reputation: 887148

We could get the combnations of the vector ('v1') for 1 to 3 'm' in a loop (lapply), paste them to a single string (toString), unlist, replicate the it twice into a list and apply expand.grid on it

expand.grid(replicate(2, unlist(c(".", lapply(1:3, 
  function(i) combn(v1, i, FUN = toString)))), simplify = FALSE))

data

v1 <- c("PD", "MO", "K")

Upvotes: 3

Related Questions