[R] How to draw 4 random weights that sum up to 1?

Uwe Ligges ligges at statistik.tu-dortmund.de
Mon Oct 10 18:44:30 CEST 2011



On 10.10.2011 18:10, Alexander Engelhardt wrote:
> Hey list,
>
> This might be a more general question and not that R-specific. Sorry for
> that.
>
> I'm trying to draw a random vector of 4 numbers that sum up to 1.
> My first approach was something like
>
> a <- runif(1)
> b <- runif(1, max=1-a)
> c <- runif(1, max=1-a-b)
> d <- 1-a-b-c
>
> but this kind of distorts the results, right?
> Would the following be a good approach?
>
> w <- sample(1:100, 4, replace=TRUE)
> w <- w/sum(w)

Yes, although better combine both ways to

w <- runif(4)
w <- w / sum(w)

Uwe Ligges



> I'd prefer a general algorithm-kind of answer to a specific R function
> (if there is any). Although a function name would help too, if I can
> sourcedive.




>
> Thanks in advance,
> Alex
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list