RobinvG - 7 months ago 21

R Question

I am stuck in a mathematical problem. I would like to make a function that outputs all the ways an integer "n" can be divide into "k" groups in such a way that in each group "k" is at least 1 (k >= 1).

The function could look something like:

`n_ways <- function(n,k) {...}`

I would like a dataFrame as an output. So for:

`A B C`

1 3 1 1

2 1 3 1

3 1 1 3

4 2 2 1

5 2 1 2

6 1 2 2

The order in which the solutions are presented in the dataFrame is not important.

I looked for solutions like here and in other languages like here and here. Unfortunately I am not that good to make a function that suits my problem based on this, but hopefully you are.

Thanks a lot in advance!

Answer

You can use the `partitions`

package:

```
library(partitions)
t(compositions(5,3,FALSE))
#[1,] 3 1 1
#[2,] 2 2 1
#[3,] 1 3 1
#[4,] 2 1 2
#[5,] 1 2 2
#[6,] 1 1 3
```

From the respective help file

Function compositions() returns all 2^(n-1) ways of partitioning an integer; thus 4+1+1 is distinct from 1+4+1 or 1+1+4.