Uses alias method (with the Robin Hood setup algorithm) for simulating a discrete/categorical probability distribution (that takes on only a finite number of values) from its probability mass function.

rpmf.alias(x, prob = 1/length(x), n = 1000, as.factor = FALSE)

Arguments

x

numeric vector giving the possible values of the discrete random variable.

prob

numeric vector giving the probabilities corresponding to x.

n

number of observations to generate.

as.factor

logical; if TRUE, the returned vector is encoded as a factor with levels x.

Value

Returns a numeric vector, or a factor if as.factor = TRUE, with the random deviates.

Examples

set.seed(1)
# Simulation of a binomial distribution
n <- 10
p <- 0.5
nsim <- 10^5
x <- 0:n
pmf <- dbinom(x, n, p)
rx <- rpmf.alias(x, pmf, nsim)
# Relative frequency plot
plot(table(rx)/nsim, ylab = "Relative frequency", xlab = "Value")
abline(v = mean(rx))
# Theoretical values
points(x, pmf, pch = 4, col = "blue")
abline(v = p*n, lty = 2, col = "blue")