Sample with a max

前端 未结 5 1191
日久生厌
日久生厌 2021-01-19 01:57

If I want to sample numbers to create a vector I do:

set.seed(123)
x <- sample(1:100,200, replace = TRUE)
sum(x)
# [1] 10228

What if I

5条回答
  •  太阳男子
    2021-01-19 02:38

    Assuming that you want integers (if not then look at the Dirichlet distribution) then this can be thought of as a ball and urn problem (without further restrictions on relationship between the numbers).

    If you want 20 numbers then that can be represented by 20 urns. You want the numbers to sum to 100 so that is 100 balls. Since you want exactly 20 numbers (skip this step if you want up to 20 numbers, but could be fewer) you start by placing 1 ball in each urn, then randomly distribute the remaining balls between the urns. Count the number of balls in each urn and you will have 20 numbers that sum to 100.

    As R code:

    as.vector(table( c( 1:20, sample(1:20, 80, replace=TRUE) ) ))
    

    The as.vector just strips off the table class and labels.

    Quick, simple, exact, no loops, recursion, etc.

    For other totals or number of values just change the appropriate pieces above.

提交回复
热议问题