Learn R Programming

extraDistr (version 1.8.1)

Categorical: Categorical distribution

Description

Probability mass function, distribution function, quantile function and random generation for the categorical distribution.

Usage

dcat(x, prob, log = FALSE)
pcat(q, prob, lower.tail = TRUE, log.p = FALSE)
qcat(p, prob, lower.tail = TRUE, log.p = FALSE, labels)
rcat(n, prob, labels)

Arguments

x, q
vector of quantiles.
prob
vector of length $k$, or $k$-column matrix of probabilities. Probabilities need to sum up to 1.
log, log.p
logical; if TRUE, probabilities p are given as log(p).
lower.tail
logical; if TRUE (default), probabilities are $P[X \le x]$ otherwise, $P[X > x]$.
p
vector of probabilities.
labels
if provided, labeled factor vector is returned. Number of labels needs to be the same as number of categories (number of columns in prob).
n
number of observations. If length(n) > 1, the length is taken to be the number required.

Examples

Run this code

# Generating 10 random draws from categorical distribution
# with k=3 categories occuring with equal probabilities
# parametrized using a vector

rcat(10, c(1/3, 1/3, 1/3))

# or with k=5 categories parametrized using a matrix of probabilities
# (generated from Dirichlet distribution)

p <- rdirichlet(10, c(1, 1, 1, 1, 1))
rcat(10, p)

x <- rcat(1e5, c(0.2, 0.4, 0.3, 0.1))
plot(prop.table(table(x)), type = "h")
lines(0:5, dcat(0:5, c(0.2, 0.4, 0.3, 0.1)), col = "red")

Run the code above in your browser using DataLab