R/shan.R

Defines functions shan

Documented in shan

#' @name shan
#' @title Calculate Shannon diversity of transitions.
#' @description Calculate the diversity of transitions using the
#' Shannon index. Note that the formulas are conditional to omit zero
#' probability values from the calculation.
#' @param p Either an array of marginal probabilities of a variable,
#' \eqn{X}, or a matrix indicating the joint probabilities across
#' all interactions of \eqn{X} and \eqn{Y} in the form:
#' \if{html}{
#'   \tabular{ccccc}{
#'   p(x,y) \tab      \tab X    \tab      \tab    \cr
#'          \tab 0.06 \tab 0.06 \tab 0.06 \tab \dots\cr
#'   Y      \tab 0.14 \tab 0.14 \tab 0.14 \tab \dots\cr
#'          \tab 0.12 \tab 0.12 \tab 0.14 \tab \dots\cr
#'          \tab \dots  \tab \dots  \tab \dots  \tab \dots
#'   }
#' }
#' \if{latex}{
#'   \deqn{
#'     \left(
#'       \begin{array}{cccc}
#'   0.06 & 0.06 & 0.06 & \dots \\
#'   0.14 & 0.14 & 0.14 & \dots \\
#'   0.12 & 0.12 & 0.14 & \dots \\
#'   \vdots & \vdots & \vdots & \ddots
#'         \end{array}\right)
#'   }
#' }
#' @details Multiply (element-wise) array (or matrix) \code{p} by logarithm
#' base 2 \code{p} and sum.
#' \deqn{\sum_i \sum_j -p(x_i,y_j) * log2 p(x_i,y_j)}{\sum -p(x_i,y_j) * log2 p(x_i,y_j) = -p(1,1) * log2 p(1,1) + -p(1,2) * log2 p(1,2) + \dots + -p(i,j) * log2 p(i,j)}
#' @return Returns a value indicating the Shannon diversity of transitions.
#' @examples
#' data(transitions)                # Load example data
#' b <- brkpts(transitions$phenofr, # Find 10 probabilistically
#'             10)                  #  equivalent breakpoints
#' m <- xt(transitions,             # Make transition matrix
#'         fr.col=2, to.col=3,
#'         cnt.col=4, brk=b)
#' pxy <- jpmf(m)                   # Joint distribution
#' hxy <- shan(pxy)                 # Shannon diversity of all transitions
#' rmd <- rowSums(pxy)              # Row marginal distribution
#' hy <- shan(rmd)                  # Shannon div of all "to" transitions
#' cmd <- colSums(pxy)              # Column marginal distribution
#' hx <- shan(cmd)                  # Shannon div of all "from" transitions
#' @author Bjorn J. Brooks, Lars Y. Pomara, Danny C. Lee
#' @references PAPER TITLE.
#' @export

shan <- function(p) {
  output <- -sum(p * log2(p), na.rm=TRUE)        # Shannon diversity

  return(output)
}
bjornbrooks/landat documentation built on May 17, 2019, 7:32 p.m.