1

My goal is to divide a list into n groups in all possible combinations (where the group has a variable length).

I found the same question answered here (Python environment), but I'm unable to replicate it in the R environment.

Could anyone kindly help me? Thanks a lot.

1 Answers1

1

If you want an easy implementation for the similar objective, you can try listParts from package partitions, e.g.,

> x <- 4

> partitions::listParts(x)
[[1]]
[1] (1,2,3,4)

[[2]]
[1] (1,2,4)(3)

[[3]]
[1] (1,2,3)(4)

[[4]]
[1] (1,3,4)(2)

[[5]]
[1] (2,3,4)(1)

[[6]]
[1] (1,4)(2,3)

[[7]]
[1] (1,2)(3,4)

[[8]]
[1] (1,3)(2,4)

[[9]]
[1] (1,4)(2)(3)

[[10]]
[1] (1,2)(3)(4)

[[11]]
[1] (1,3)(2)(4)

[[12]]
[1] (2,4)(1)(3)

[[13]]
[1] (2,3)(1)(4)

[[14]]
[1] (3,4)(1)(2)

[[15]]
[1] (1)(2)(3)(4)

where x is the number of elements in the set, and all partitions denotes the indices of elements.


If you want to choose the number of partitions, below is a user function that may help

f <- function(x, n) {
  res <- listParts(x)
  subset(res, lengths(res) == n)
}

such that

> f(x, 2)
[[1]]
[1] (1,2,4)(3)

[[2]]
[1] (1,2,3)(4)

[[3]]
[1] (1,3,4)(2)

[[4]]
[1] (2,3,4)(1)

[[5]]
[1] (1,4)(2,3)

[[6]]
[1] (1,2)(3,4)

[[7]]
[1] (1,3)(2,4)


> f(x, 3)
[[1]]
[1] (1,4)(2)(3)

[[2]]
[1] (1,2)(3)(4)

[[3]]
[1] (1,3)(2)(4)

[[4]]
[1] (2,4)(1)(3)

[[5]]x
[1] (2,3)(1)(4)

[[6]]
[1] (3,4)(1)(2)

Update Given x <- LETTERS[1:4], we can run

res <- rapply(listParts(length(x)), function(v) x[v], how = "replace")

such that

> res
[[1]]
[1] (A,B,C,D)

[[2]]
[1] (A,B,D)(C)

[[3]]
[1] (A,B,C)(D)

[[4]]
[1] (A,C,D)(B)

[[5]]
[1] (B,C,D)(A)

[[6]]
[1] (A,D)(B,C)

[[7]]
[1] (A,B)(C,D)

[[8]]
[1] (A,C)(B,D)

[[9]]
[1] (A,D)(B)(C)

[[10]]
[1] (A,B)(C)(D)

[[11]]
[1] (A,C)(B)(D)

[[12]]
[1] (B,D)(A)(C)

[[13]]
[1] (B,C)(A)(D)

[[14]]
[1] (C,D)(A)(B)

[[15]]
[1] (A)(B)(C)(D)

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Thank you for your answer. Is there a way to decide the n groups? for example with n = 2 we have: [(1), (2,3,4)] [(2), (1,3,4)] [(3), (1,2,4)] [(4), (1,2,3)] [(1,2), (3,4)] [(1.3), (2.4)] [(1.4), (2.3)] while with n = 3 [(1), (2), (3,4)] [(1), (3), (2.4)] [(1), (4), (2,3)] [(2), (3), (1.4)] [(2), (4), (1,3)] [(3), (4), (1,2)] – GN_Agostino Jan 11 '21 at 23:47
  • Perfect! Thanks so much again !! – GN_Agostino Jan 12 '21 at 06:57
  • if I have a character vector like this x <- LETTERS(1:4) instead of a vector x <- 4 how can I perform the same combination? – GN_Agostino Jan 12 '21 at 17:20
  • 1
    @GN_Agostino I updated my answer, where `rapply` is used. – ThomasIsCoding Jan 12 '21 at 22:34