simplex.sample: Sample uniformly from a simplex

View source: R/sample.R

simplex.sampleR Documentation

Sample uniformly from a simplex

Description

Generates uniform random variates over the (n-1)-simplex in n-dimensional space.

Usage

simplex.sample(n, N, sort=FALSE)

Arguments

n

Dimension of the space

N

Number of samples to generate

sort

Whether to sort the components in descending order

Details

The samples will be uniform over the (n-1)-simplex.

Value

samples

A matrix containing the generated samples as rows.

Author(s)

Gert van Valkenhoef

Examples

n <- 3
N <- 10000
samples <- simplex.sample(n, N)$samples

# Check dimension
stopifnot(dim(samples) == c(N, n))

# Check that w_i >= 0
stopifnot(samples >= 0)

# Check that sum_i w_i = 1
E <- 1E-12
stopifnot(apply(samples, 1, sum) > 1 - E)
stopifnot(apply(samples, 1, sum) < 1 + E)


## Now with descending order
samples <- simplex.sample(n, N, sort=TRUE)$samples

# Check dimension
stopifnot(dim(samples) == c(N, n))

# Check that w_i >= 0
stopifnot(samples >= 0)

# Check that sum_i w_i = 1
E <- 1E-12
stopifnot(apply(samples, 1, sum) > 1 - E)
stopifnot(apply(samples, 1, sum) < 1 + E)

# Check w_i >= w_{i+1}
stopifnot(samples[,1] >= samples[,2])
stopifnot(samples[,2] >= samples[,3])

hitandrun documentation built on May 28, 2022, 1:09 a.m.