Generate 3 random number that sum to 1 in R

前端 未结 6 1161
花落未央
花落未央 2020-12-16 18:15

I am hoping to create 3 (non-negative) quasi-random numbers that sum to one, and repeat over and over.

Basically I am trying to partition something into three rand

6条回答
  •  一整个雨季
    2020-12-16 18:50

    I guess it depends on what distribution you want on the numbers, but here is one way:

    diff(c(0, sort(runif(2)), 1))
    

    Use replicate to get as many sets as you want:

    > x <- replicate(5, diff(c(0, sort(runif(2)), 1)))
    > x
               [,1]       [,2]      [,3]      [,4]       [,5]
    [1,] 0.66855903 0.01338052 0.3722026 0.4299087 0.67537181
    [2,] 0.32130979 0.69666871 0.2670380 0.3359640 0.25860581
    [3,] 0.01013117 0.28995078 0.3607594 0.2341273 0.06602238
    > colSums(x)
    [1] 1 1 1 1 1
    

提交回复
热议问题