2

How do I randomly partition an integer into n parts, with zero a possible outcome? (Preferably in R)

For example, to partition the integer number 5 into 3 parts and do this 4 times, I might get this output:

[1] 4 0 1

[2] 2 2 1

[3] 0 2 3

[4] 1 1 3 

Thanks!

Pierre L
  • 27,528
  • 5
  • 43
  • 64
VeBeKay
  • 21
  • 1
  • Are you just looking for `sample(x, size, replace)`? This randomly draws `size` elements from `x`. `sample(0:5, 3, TRUE)`. To do this 4 times, use `replicate(4, sample(0:5, 3, TRUE))` (or just draw 4*3=12 elements and split the vector into 4 parts). – CL. Jul 13 '15 at 14:46
  • Not quite.. I had looked at the sample() function before, but I don't think it's doing what I need. I want the sum of all elements of the partition to be a given number (5, in my example) , and randomly generate these partitions. One way might be to write out all possible partitions, and then use a random number generator to choose a partition. However, the number of possible partitions gets very large for large integers, and this might be a problem. – VeBeKay Jul 13 '15 at 14:58
  • And what is the difference between what it does and what you need? Maybe you can clarify the question a little. – CL. Jul 13 '15 at 15:00
  • sorry, I hit enter before I was done explaining... – VeBeKay Jul 13 '15 at 15:03
  • `expand.grid(0:5, 0:5,0:5)[rowSums(expand.grid(0:5, 0:5,0:5))==5, ]` will give you the all possible triplets adds up to 5. You can now use `sample`. – Khashaa Jul 13 '15 at 15:07
  • also see here http://stackoverflow.com/a/27064925/3573401 – Khashaa Jul 13 '15 at 15:18
  • Thanks, Khashaa, I think that's doing what I need! – VeBeKay Jul 13 '15 at 15:26

1 Answers1

2
library(partitions)
t(restrictedparts(5, 3))
[1,] 5 0 0
[2,] 4 1 0
[3,] 3 2 0
[4,] 3 1 1
[5,] 2 2 1

There are other helpful functions in that package. This document will walk through random sampling and combinatorials link here.

Pierre L
  • 27,528
  • 5
  • 43
  • 64