[R] Random number generation
djnordlund at frontier.com
Fri Jul 22 09:05:45 CEST 2011
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
> On Behalf Of Dennis Murphy
> Sent: Thursday, July 21, 2011 8:55 PM
> To: karena
> Cc: r-help at r-project.org
> Subject: Re: [R] Random number generation
> 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)))
>  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
> 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
> 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.
> 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
if you search the R-help archive you will find a couple of threads discussing this topic. Here is one URL to get you started.
Hope this is helpful,
Bothell, WA USA
More information about the R-help