[R] How to draw 4 random weights that sum up to 1?
Greg Snow
Greg.Snow at imail.org
Mon Oct 10 18:42:13 CEST 2011
You probably want to generate data from a Dirichlet distribution. There are some functions in packages that will do this and give you more background, or you can just generate 4 numbers from an exponential (or gamma) distribution and divide them by their sum.
--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Alexander Engelhardt
> Sent: Monday, October 10, 2011 10:11 AM
> To: r-help
> Subject: [R] How to draw 4 random weights that sum up to 1?
>
> 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)
>
> 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