0

I would like to generate N random integers that sum to M and each integer must be randomly chosen from a uniform distribution.

My first idea was:

1) To enumerate different partitions of M, then

2) To randomly permute the elements of a vector

Here is my code to do this:

library(partitions) 
library(gtools) 
N <- 10
M <- 5
x <- t(restrictedparts(M, N)) 
x <- split(x, seq(nrow(x))) 
xp <- permute(x[[sample(1:length(x), 1)]]) 

However, I am not sure that my idea is correct because each integer is not randomly chosen from a uniform distribution and the code is too long when M >= 100. Is there a way to do this?

Related questions in Python

Generating N uniform random numbers that sum to M

Generate multiple random numbers to equal a value in python

Pierre
  • 435
  • 4
  • 14
  • Let me know if your question is different from the marked duplicated one. There are also some other links in the duplicated question, have a look at them as well. – Ronak Shah Jul 17 '18 at 03:36
  • I think the right duplicate would be https://stackoverflow.com/q/5622608/8416610. See also the wiki for the random tag. – Ralf Stubner Jul 17 '18 at 04:40
  • 1
    Agree with Ralf. Modified the duplicate citation. Also see the discussion on Rhelp last week. Maybe the paper "Acceptance–Rejection Sampling from the Conditional Distribution of Independent Discrete Random Variables, given their Sum", Statistics 34, pages 247-257 offered by Göran Broström. – IRTFM Jul 17 '18 at 05:32
  • Thanks for your replies. Compared to the duplicated question, the sum of random integers is not only equal to 1 (M can be >= 1). – Pierre Jul 17 '18 at 14:25
  • It seems to me that converting the logic in the nominated duplicate to have the result sum to M should be trivial. – IRTFM Jul 17 '18 at 15:46
  • The scaling is indeed trivial. More complicated is the need for integers. Instead of drawing random numbers with runif one would create N - 1 random integers with sample. – Ralf Stubner Jul 17 '18 at 17:21

0 Answers0