% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/discrete-summaries.R
\name{entropy}
\alias{entropy}
\alias{entropy.default}
\alias{entropy.rvar}
\title{Normalized entropy}
\usage{
entropy(x)

\method{entropy}{default}(x)

\method{entropy}{rvar}(x)
}
\arguments{
\item{x}{(multiple options) A vector to be interpreted as draws from
a categorical distribution, such as:
\itemize{
\item A \link{factor}
\item A \link{numeric} (should be \link{integer} or integer-like)
\item An \link{rvar}, \link{rvar_factor}, or \link{rvar_ordered}
}}
}
\value{
If \code{x} is a \link{factor} or \link{numeric}, returns a length-1 numeric vector with a value
between 0 and 1 (inclusive) giving the normalized Shannon entropy of \code{x}.

If \code{x} is an \link{rvar}, returns an array of the same shape as \code{x}, where each
cell is the normalized Shannon entropy of the draws in the corresponding cell of \code{x}.
}
\description{
Normalized entropy, for measuring dispersion in draws from categorical distributions.
}
\details{
Calculates the normalized Shannon entropy of the draws in \code{x}. This value is
the entropy of \code{x} divided by the maximum entropy of a distribution with \code{n}
categories, where \code{n} is \code{length(unique(x))} for numeric vectors and
\code{length(levels(x))} for factors:

\deqn{-\frac{\sum_{i = 1}^{n} p_i \log(p_i)}{\log(n)}}

This scales the output to be between 0 (all probability in one category)
and 1 (uniform). This form of normalized entropy is referred to as
\eqn{H_\mathrm{REL}} in Wilcox (1967).
}
\examples{
set.seed(1234)

levels <- c("a", "b", "c", "d", "e")

# a uniform distribution: high normalized entropy
x <- factor(
  sample(levels, 4000, replace = TRUE, prob = c(0.2, 0.2, 0.2, 0.2, 0.2)),
  levels = levels
)
entropy(x)

# a unimodal distribution: low normalized entropy
y <- factor(
  sample(levels, 4000, replace = TRUE, prob = c(0.95, 0.02, 0.015, 0.01, 0.005)),
  levels = levels
)
entropy(y)

# both together, as an rvar
xy <- c(rvar(x), rvar(y))
xy
entropy(xy)
}
\references{
Allen R. Wilcox (1967). \emph{Indices of Qualitative Variation}
(No. ORNL-TM-1919). Oak Ridge National Lab., Tenn.
}
