Uses the guide table aided inversion method (also know as indexed search method) for simulating a discrete/categorical probability distribution (that takes on only a finite number of values) from its probability mass function.

rpmf.table(x, prob = 1/length(x), m, 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.

m

size of the table with starting points for the search.

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 and an attribute ncomp with the required number of comparisons in the sequential search.

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.table(x, pmf, n-1, 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")

# Number of comparisons
ncomp <- attr(rx, "ncomp")
ncomp/nsim # mean number
#> [1] 0.55951
sum((1:length(x))*pmf) # theoretical expected number with sequential search
#> [1] 6