Learn R Programming

MetabolSSMF (version 0.1.0)

diversity: Shannon diversity index

Description

Calculate the Shannon diversity index of the memberships of an observation. The base of the logarithm is 2.

Usage

diversity(x, two.power = FALSE)

Value

A numeric value of Shannon diversity index \(\mathrm{E}(h_{i})\) or \(2^{\mathrm{E}(h_{i})}\).

Arguments

x

A membership vector.

two.power

Logical, whether return to the value of \(2^{\mathrm{E}(h_{i})}\).

Author

Wenxuan Liu

Details

Given a membership vector of the \(i^{th}\) observation \(h_i\), the Shannon diversity index is defined as $$\mathrm{E}(h_{i}) = -\sum_{r=1}^k h_{ir} \mathrm{log}_2 (h_{ir}).$$ Specifically, in the case of \(h_{ir}=0\), the value of \(h_{ir} \mathrm{log}_2 (h_{ir})\) is taken to be 0.

Examples

Run this code
# Memberships vector
membership1 <- c(0.1, 0.2, 0.3, 0.4)
diversity(membership1)
diversity(membership1, two.power = TRUE)

# Memberships matrix
membership2 <- matrix(c(0.1, 0.2, 0.3, 0.4, 0.3, 0.2, 0.4, 0.1, 0.2, 0.3, 0.1, 0.4),
                      nrow=3, ncol=4, byrow=TRUE)

E <- rep(NA, nrow(membership2))
for(i in 1:nrow(membership2)){
  E[i] <- diversity(membership2[i,])
}
E

Run the code above in your browser using DataLab