Hi:
Here's one way using uniform(0, 1) pseudo-random numbers, but there
are many ways you could go about this.
# each row comprises a set of three pseudo-random numbers
u <- matrix(runif(30), nrow = 10)
# divide each element in a row by its row sum
v <- t(apply(u, 1, function(x) x/sum(x)))
rowSums(v)
[1] 1 1 1 1 1 1 1 1 1 1
# An equivalent way (about equally fast) is
u/outer(rowSums(u), rep(1, 3))
Now try
hist(unlist(v))
and notice that the distribution of the constrained sets is not really
uniform. This is a consequence of setting a constraint on the sum of
each sample. Another way to see this is to plot
plot(sort(unlist(v)))
A 'truly' uniform random sample would lie approximately on a straight
line in this plot.
It would seem to me that a better approach would be to sample from a
simplex embedded in the unit cube. I'd suggest looking into the
compositions package (because you are effectively generating
compositional data) and look into its capabilities. At least a couple
of the references in the package's overview page seem to be germane to
the problem.
The pair of runif.* functions appear to be relevant.
HTH,
Dennis
On Thu, Jul 21, 2011 at 4:18 PM, karena <dr.jzhou at gmail.com>
wrote:> Hi,
>
> I want to generate multiple sets of random numbers.
> The requirement is that:
> 1) each set have 3 random numbers;
> 2) the sum of the three number is always 1.
>
> how to do this?
>
> thank you,
>
> karena
>
> --
> View this message in context:
http://r.789695.n4.nabble.com/Random-number-generation-tp3685463p3685463.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>