Search code examples
rcombinatorics

List all ways to draw n numbers with replacement out of m < n values (i.o.w.: all partitionings of a set of size n into m distinct subsets) in R


In a simulation study, I need to generate all distinct ways to generate a sequence of m numbers between 1 and n (n>m) such that the sum of the numbers is n, i.e.

nums <- c(n_1, n_2, ..., n_m)

with the constraints

min(num) > 0 & sum(nums) == n

In other words: the possible partitionings of a set of n elemnts into m distinct subsets. I know that the number of such partitions is the "Stirling number of the second kind", which makes this infeasible for large n, but I will need it for small n.

Note that this a different problem from finding all permutations, which is answered in this thread. It is instead about partitioning.


Solution

  • From the partitions package (GitHub), partitions::compositions(n, m, include.zero) should do the trick. Here, n would represent what each vector should sum up to, m the number of elements of that vector, and include.zero=FALSE ensures that there's no zeros.

    partitions::compositions(n=5, m=2, include.zero=FALSE) |> t()
    # [1,] 4 1
    # [2,] 3 2
    # [3,] 2 3
    # [4,] 1 4