Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i split a number randomly into multiple numbers given the number and n groups?

For instance , if the number is 100 and the number of groups is 4 it should give any random list of 4 numbers that add upto 100:

input number = 100

number of groups = 4

Possible outputs:

25, 25, 25, 25

10, 20, 30, 40

15, 35, 2, 48

The output should only be one list generated. More application oriented example would be how i would split a probability 1 into multiple groups given the number of groups using R?

like image 359
Abhilash Avatar asked Dec 25 '22 09:12

Abhilash


2 Answers

rmultinom might be handy here:

x <- rmultinom(n = 1, size = 100, prob = rep(1/4, 4))
x
colSums(x)

Here I draw one vector, with a total size of 100, which is splitted into 4 groups.

like image 94
EDi Avatar answered Jan 31 '23 01:01

EDi


You can try following

total <- 100
n <- 4
as.vector(table(sample(1:n, size = total, replace = T)))
## [1] 23 27 24 26

as.vector(table(sample(1:n, size = total, replace = T)))
## [1] 25 26 28 21

as.vector(table(sample(1:n, size = total, replace = T)))
## [1] 24 20 28 28
like image 24
CHP Avatar answered Jan 31 '23 01:01

CHP