Uses the inverse transform method with sequential search for simulating a discrete/categorical probability distribution (that takes on only a finite number of values) from its probability mass function.

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



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


numeric vector giving the probabilities corresponding to x.


number of observations to generate.


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


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.


# Simulation of a binomial distribution
n <- 10
p <- 0.5
nsim <- 10^5
x <- 0:n
pmf <- dbinom(x, n, p)
rx <- rpmf(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")

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