rdiversity examples

Sonia Mitchell

December 03 2026

Generating a metacommunity

Before calculating diversity a metacommunity object must be created. This object contains all the information needed to calculate diversity. In the following example, we generate a metacommunity (partition) comprising two species (“cows” and “sheep”), and partitioned across three subcommunities (a, b, and c).

# Load the package into R
library(rdiversity)

# Initialise data
partition <- data.frame(a = c(1, 1), b = c(2, 0), c = c(3, 1))
row.names(partition) <- c("cows", "sheep")

The metacommunity() function takes two arguments, partition and similarity. When species are considered completely distinct, an identity matrix is required, which is generated automatically if the similarity argument is missing, as below:

# Generate metacommunity object
meta <- metacommunity(partition = partition)

Note that a warning is displayed when abundances (rather than relative abundances) are entered into the partition argument. Both are acceptable inputs.

When species share some similarity and a similarity matrix is available, then a similarity object (and the metacommunity object) is generated in the following way:

# Initialise similarity matrix
s <- matrix(c(1, 0.5, 0.5, 1), nrow = 2)
row.names(s) <- c("cows", "sheep")
colnames(s) <- c("cows", "sheep")

# Generate similarity object
s <- similarity(similarity = s, dat_id = "my_taxonomic")

# Generate metacommunity object
meta <- metacommunity(partition = partition, similarity = s)

Alternatively, if a distance matrix is available, then a distance object is generated in the following way:

# Initialise distance matrix
d <- matrix(c(0, 0.7, 0.7, 0), nrow = 2)
row.names(d) <- c("cows", "sheep")
colnames(d) <- c("cows", "sheep")

# Generate distance object
d <- distance(distance = d, dat_id = "my_taxonomic")

# Convert the distance object to similarity object (by means of a linear or exponential transform)
s <- dist2sim(dist = d, transform = "linear")

# Generate metacommunity object
meta <- metacommunity(partition = partition, similarity = s)

Each metacommunity object contains the following slots:

Calculating diversity

Method 1

This method uses a wrapper function to simplify the pipeline and is recommended if only a few measures are being calculated.

A complete list of these functions is shown below:

Each of these functions take two arguments, meta (a metacommunity object) and qs (a vector of q values), and output results as a rdiv object. For example, to calculate normalised subcommunity alpha diversity for q=0, q=1, and q=2:

# Initialise data
partition <- data.frame(a = c(1, 1), b = c(2, 0), c = c(3, 1))
row.names(partition) <- c("cows", "sheep")

# Generate a metacommunity object
meta <- metacommunity(partition)

# Calculate diversity
norm_sub_alpha(meta, 0:2)
##   div_type         measure q type_level type_name partition_level
## 1   Unique NormalisedAlpha 0      types              subcommunity
## 2   Unique NormalisedAlpha 0      types              subcommunity
## 3   Unique NormalisedAlpha 0      types              subcommunity
## 4   Unique NormalisedAlpha 1      types              subcommunity
## 5   Unique NormalisedAlpha 1      types              subcommunity
## 6   Unique NormalisedAlpha 1      types              subcommunity
## 7   Unique NormalisedAlpha 2      types              subcommunity
## 8   Unique NormalisedAlpha 2      types              subcommunity
## 9   Unique NormalisedAlpha 2      types              subcommunity
##   partition_name diversity transformation normalised  k max_d
## 1              a  2.000000             NA         NA NA    NA
## 2              b  1.000000             NA         NA NA    NA
## 3              c  2.000000             NA         NA NA    NA
## 4              a  2.000000             NA         NA NA    NA
## 5              b  1.000000             NA         NA NA    NA
## 6              c  1.754765             NA         NA NA    NA
## 7              a  2.000000             NA         NA NA    NA
## 8              b  1.000000             NA         NA NA    NA
## 9              c  1.600000             NA         NA NA    NA

However, if multiple measures are required and computational efficiency is an issue, then the following method is recommended (the same results are obtained).

Method 2

This method requires that we first calculate the species-level components, by passing a metacommunity object to the appropriate function; raw_alpha(), norm_alpha(), raw_beta(), norm_beta(), raw_rho(), norm_rho(), or raw_gamma(). Subcommunity- and metacommunity-level diversities are calculated using the functions subdiv() and metadiv(). Since both subcommunity and metacommunity diversity measures are transformations of the same species-level component, this method is computationally more efficient.

# Initialise data
partition <- data.frame(a = c(1, 1), b = c(2, 0), c = c(3, 1))
row.names(partition) <- c("cows", "sheep")

# Generate a metacommunity object
meta <- metacommunity(partition)

# Calculate the species-level component for normalised alpha
component <- norm_alpha(meta)

# Calculate normalised alpha at the subcommunity-level
subdiv(component, 0:2)
##   div_type         measure q type_level type_name partition_level
## 1   Unique NormalisedAlpha 0      types              subcommunity
## 2   Unique NormalisedAlpha 0      types              subcommunity
## 3   Unique NormalisedAlpha 0      types              subcommunity
## 4   Unique NormalisedAlpha 1      types              subcommunity
## 5   Unique NormalisedAlpha 1      types              subcommunity
## 6   Unique NormalisedAlpha 1      types              subcommunity
## 7   Unique NormalisedAlpha 2      types              subcommunity
## 8   Unique NormalisedAlpha 2      types              subcommunity
## 9   Unique NormalisedAlpha 2      types              subcommunity
##   partition_name diversity transformation normalised  k max_d
## 1              a  2.000000             NA         NA NA    NA
## 2              b  1.000000             NA         NA NA    NA
## 3              c  2.000000             NA         NA NA    NA
## 4              a  2.000000             NA         NA NA    NA
## 5              b  1.000000             NA         NA NA    NA
## 6              c  1.754765             NA         NA NA    NA
## 7              a  2.000000             NA         NA NA    NA
## 8              b  1.000000             NA         NA NA    NA
## 9              c  1.600000             NA         NA NA    NA
# Likewise, calculate normalised alpha at the metacommunity-level
metadiv(component, 0:2)
##   div_type         measure q type_level type_name partition_level
## 1   Unique NormalisedAlpha 0      types             metacommunity
## 2   Unique NormalisedAlpha 1      types             metacommunity
## 3   Unique NormalisedAlpha 2      types             metacommunity
##   partition_name diversity transformation normalised  k max_d
## 1                 1.750000             NA         NA NA    NA
## 2                 1.575314             NA         NA NA    NA
## 3                 1.454545             NA         NA NA    NA

In some instances, it may be useful to calculate all subcommunity (or metacommunity) measures. In which case, a metacommunity object may be passed directly to subdiv() or metadiv():

# Calculate all subcommunity diversity measures
subdiv(meta, 0:2)
##    div_type         measure q type_level type_name partition_level
## 1    Unique        RawAlpha 0      types              subcommunity
## 2    Unique        RawAlpha 0      types              subcommunity
## 3    Unique        RawAlpha 0      types              subcommunity
## 4    Unique        RawAlpha 1      types              subcommunity
## 5    Unique        RawAlpha 1      types              subcommunity
## 6    Unique        RawAlpha 1      types              subcommunity
## 7    Unique        RawAlpha 2      types              subcommunity
## 8    Unique        RawAlpha 2      types              subcommunity
## 9    Unique        RawAlpha 2      types              subcommunity
## 10   Unique NormalisedAlpha 0      types              subcommunity
## 11   Unique NormalisedAlpha 0      types              subcommunity
## 12   Unique NormalisedAlpha 0      types              subcommunity
## 13   Unique NormalisedAlpha 1      types              subcommunity
## 14   Unique NormalisedAlpha 1      types              subcommunity
## 15   Unique NormalisedAlpha 1      types              subcommunity
## 16   Unique NormalisedAlpha 2      types              subcommunity
## 17   Unique NormalisedAlpha 2      types              subcommunity
## 18   Unique NormalisedAlpha 2      types              subcommunity
## 19   Unique         RawBeta 0      types              subcommunity
## 20   Unique         RawBeta 0      types              subcommunity
## 21   Unique         RawBeta 0      types              subcommunity
## 22   Unique         RawBeta 1      types              subcommunity
## 23   Unique         RawBeta 1      types              subcommunity
## 24   Unique         RawBeta 1      types              subcommunity
## 25   Unique         RawBeta 2      types              subcommunity
## 26   Unique         RawBeta 2      types              subcommunity
## 27   Unique         RawBeta 2      types              subcommunity
## 28   Unique  NormalisedBeta 0      types              subcommunity
## 29   Unique  NormalisedBeta 0      types              subcommunity
## 30   Unique  NormalisedBeta 0      types              subcommunity
## 31   Unique  NormalisedBeta 1      types              subcommunity
## 32   Unique  NormalisedBeta 1      types              subcommunity
## 33   Unique  NormalisedBeta 1      types              subcommunity
## 34   Unique  NormalisedBeta 2      types              subcommunity
## 35   Unique  NormalisedBeta 2      types              subcommunity
## 36   Unique  NormalisedBeta 2      types              subcommunity
## 37   Unique          RawRho 0      types              subcommunity
## 38   Unique          RawRho 0      types              subcommunity
## 39   Unique          RawRho 0      types              subcommunity
## 40   Unique          RawRho 1      types              subcommunity
## 41   Unique          RawRho 1      types              subcommunity
## 42   Unique          RawRho 1      types              subcommunity
## 43   Unique          RawRho 2      types              subcommunity
## 44   Unique          RawRho 2      types              subcommunity
## 45   Unique          RawRho 2      types              subcommunity
## 46   Unique   NormalisedRho 0      types              subcommunity
## 47   Unique   NormalisedRho 0      types              subcommunity
## 48   Unique   NormalisedRho 0      types              subcommunity
## 49   Unique   NormalisedRho 1      types              subcommunity
## 50   Unique   NormalisedRho 1      types              subcommunity
## 51   Unique   NormalisedRho 1      types              subcommunity
## 52   Unique   NormalisedRho 2      types              subcommunity
## 53   Unique   NormalisedRho 2      types              subcommunity
## 54   Unique   NormalisedRho 2      types              subcommunity
## 55   Unique           Gamma 0      types              subcommunity
## 56   Unique           Gamma 0      types              subcommunity
## 57   Unique           Gamma 0      types              subcommunity
## 58   Unique           Gamma 1      types              subcommunity
## 59   Unique           Gamma 1      types              subcommunity
## 60   Unique           Gamma 1      types              subcommunity
## 61   Unique           Gamma 2      types              subcommunity
## 62   Unique           Gamma 2      types              subcommunity
## 63   Unique           Gamma 2      types              subcommunity
##    partition_name diversity transformation normalised  k max_d
## 1               a 8.0000000             NA         NA NA    NA
## 2               b 4.0000000             NA         NA NA    NA
## 3               c 4.0000000             NA         NA NA    NA
## 4               a 8.0000000             NA         NA NA    NA
## 5               b 4.0000000             NA         NA NA    NA
## 6               c 3.5095307             NA         NA NA    NA
## 7               a 8.0000000             NA         NA NA    NA
## 8               b 4.0000000             NA         NA NA    NA
## 9               c 3.2000000             NA         NA NA    NA
## 10              a 2.0000000             NA         NA NA    NA
## 11              b 1.0000000             NA         NA NA    NA
## 12              c 2.0000000             NA         NA NA    NA
## 13              a 2.0000000             NA         NA NA    NA
## 14              b 1.0000000             NA         NA NA    NA
## 15              c 1.7547654             NA         NA NA    NA
## 16              a 2.0000000             NA         NA NA    NA
## 17              b 1.0000000             NA         NA NA    NA
## 18              c 1.6000000             NA         NA NA    NA
## 19              a 0.2500000             NA         NA NA    NA
## 20              b 0.3333333             NA         NA NA    NA
## 21              c 0.5000000             NA         NA NA    NA
## 22              a 0.2886751             NA         NA NA    NA
## 23              b 0.3333333             NA         NA NA    NA
## 24              c 0.5000000             NA         NA NA    NA
## 25              a 0.3333333             NA         NA NA    NA
## 26              b 0.3333333             NA         NA NA    NA
## 27              c 0.5000000             NA         NA NA    NA
## 28              a 1.0000000             NA         NA NA    NA
## 29              b 1.3333333             NA         NA NA    NA
## 30              c 1.0000000             NA         NA NA    NA
## 31              a 1.1547005             NA         NA NA    NA
## 32              b 1.3333333             NA         NA NA    NA
## 33              c 1.0000000             NA         NA NA    NA
## 34              a 1.3333333             NA         NA NA    NA
## 35              b 1.3333333             NA         NA NA    NA
## 36              c 1.0000000             NA         NA NA    NA
## 37              a 4.0000000             NA         NA NA    NA
## 38              b 3.0000000             NA         NA NA    NA
## 39              c 2.0000000             NA         NA NA    NA
## 40              a 3.4641016             NA         NA NA    NA
## 41              b 3.0000000             NA         NA NA    NA
## 42              c 2.0000000             NA         NA NA    NA
## 43              a 3.0000000             NA         NA NA    NA
## 44              b 3.0000000             NA         NA NA    NA
## 45              c 2.0000000             NA         NA NA    NA
## 46              a 1.0000000             NA         NA NA    NA
## 47              b 0.7500000             NA         NA NA    NA
## 48              c 1.0000000             NA         NA NA    NA
## 49              a 0.8660254             NA         NA NA    NA
## 50              b 0.7500000             NA         NA NA    NA
## 51              c 1.0000000             NA         NA NA    NA
## 52              a 0.7500000             NA         NA NA    NA
## 53              b 0.7500000             NA         NA NA    NA
## 54              c 1.0000000             NA         NA NA    NA
## 55              a 2.6666667             NA         NA NA    NA
## 56              b 1.3333333             NA         NA NA    NA
## 57              c 2.0000000             NA         NA NA    NA
## 58              a 2.3094011             NA         NA NA    NA
## 59              b 1.3333333             NA         NA NA    NA
## 60              c 1.7547654             NA         NA NA    NA
## 61              a 2.0000000             NA         NA NA    NA
## 62              b 1.3333333             NA         NA NA    NA
## 63              c 1.6000000             NA         NA NA    NA
# Calculate all metacommunity diversity measures
metadiv(meta, 0:2)
##    div_type         measure q type_level type_name partition_level
## 1    Unique        RawAlpha 0      types             metacommunity
## 2    Unique        RawAlpha 1      types             metacommunity
## 3    Unique        RawAlpha 2      types             metacommunity
## 4    Unique NormalisedAlpha 0      types             metacommunity
## 5    Unique NormalisedAlpha 1      types             metacommunity
## 6    Unique NormalisedAlpha 2      types             metacommunity
## 7    Unique         RawBeta 0      types             metacommunity
## 8    Unique         RawBeta 1      types             metacommunity
## 9    Unique         RawBeta 2      types             metacommunity
## 10   Unique  NormalisedBeta 0      types             metacommunity
## 11   Unique  NormalisedBeta 1      types             metacommunity
## 12   Unique  NormalisedBeta 2      types             metacommunity
## 13   Unique          RawRho 0      types             metacommunity
## 14   Unique          RawRho 1      types             metacommunity
## 15   Unique          RawRho 2      types             metacommunity
## 16   Unique   NormalisedRho 0      types             metacommunity
## 17   Unique   NormalisedRho 1      types             metacommunity
## 18   Unique   NormalisedRho 2      types             metacommunity
## 19   Unique           Gamma 0      types             metacommunity
## 20   Unique           Gamma 1      types             metacommunity
## 21   Unique           Gamma 2      types             metacommunity
##    partition_name diversity transformation normalised  k max_d
## 1                 5.0000000             NA         NA NA    NA
## 2                 4.4556597             NA         NA NA    NA
## 3                 4.0000000             NA         NA NA    NA
## 4                 1.7500000             NA         NA NA    NA
## 5                 1.5753136             NA         NA NA    NA
## 6                 1.4545455             NA         NA NA    NA
## 7                 0.3958333             NA         NA NA    NA
## 8                 0.3938284             NA         NA NA    NA
## 9                 0.4000000             NA         NA NA    NA
## 10                1.0833333             NA         NA NA    NA
## 11                1.1139149             NA         NA NA    NA
## 12                1.1428571             NA         NA NA    NA
## 13                2.7500000             NA         NA NA    NA
## 14                2.5391770             NA         NA NA    NA
## 15                2.4000000             NA         NA NA    NA
## 16                0.9375000             NA         NA NA    NA
## 17                0.8977346             NA         NA NA    NA
## 18                0.8571429             NA         NA NA    NA
## 19                2.0000000             NA         NA NA    NA
## 20                1.7547654             NA         NA NA    NA
## 21                1.6000000             NA         NA NA    NA

Taxonomic diversity

  1. Initialise data:
# Taxonomic lookup table
Species <- c("tenuifolium", "asterolepis", "simplex var.grandiflora", "simplex var.ochnacea")
Genus <- c("Protium", "Quararibea", "Swartzia", "Swartzia")
Family <- c("Burseraceae", "Bombacaceae", "Fabaceae", "Fabaceae")
Subclass <- c("Sapindales", "Malvales", "Fabales", "Fabales")
lookup <- cbind.data.frame(Species, Genus, Family, Subclass)

# Partition matrix
partition <- matrix(rep(1, 8), nrow = 4)
colnames(partition) <- LETTERS[1:2]
rownames(partition) <- lookup$Species

and assign values for each taxonomic level, from the lowest up, ending with a value for species that share no level:

values <- c(Species = 0, Genus = 1, Family = 2, Subclass = 3, Other = 4)
  1. Generate a distance object from a lookup table using the tax2dist() function:
d <- tax2dist(lookup, values)

By default the tax2dist() argument precompute_dist is TRUE, such that a pairwise distance matrix is calculated automatically and is stored in d@distance. If the taxonomy is too large, precompute_dist can be set to FALSE. No distance matrix is then stored, and the same diversity is calculated from the abundance of each taxon, in step 4. For more than 10,000 species tax2dist() gives an error unless precompute_dist is set.

  1. Convert the distance object to similarity object (by means of a linear or exponential transform) using the dist2sim() function:
s <- dist2sim(d, "linear")
  1. Generate a metacommunity object using the metacommunity() function:
meta <- metacommunity(partition, s)
  1. Calculate diversity:
meta_gamma(meta, 0:2)
##   div_type measure q type_level type_name partition_level partition_name
## 1 Taxonomy   Gamma 0      types             metacommunity               
## 2 Taxonomy   Gamma 1      types             metacommunity               
## 3 Taxonomy   Gamma 2      types             metacommunity               
##   diversity transformation normalised k max_d
## 1  3.142857         linear       TRUE 1     4
## 2  3.023716         linear       TRUE 1     4
## 3  2.909091         linear       TRUE 1     4

Phylogenetic diversity

The examples in this section need the ape package, and are run only where it is installed.

Phylogenetic diversity measures can be broadly split into two categories – those that look at the phylogeny as a whole, such as Faith’s (1992) phylogenetic diversity (Faith’s PD), and those that look at pairwise tip distances, such as mean pairwise distance (MPD; Webb, 2000). The framework of measures presented in this package is able to quantify phylogenetic diversity using both of these methods.

Distance-based phylogenetic diversity

  1. Initialise data:
# Example data
tree <- ape::rtree(4)
partition <- matrix(1:12, ncol = 3)
partition <- partition / sum(partition)
  1. Generate a distance matrix using the phy2dist() function:
d <- phy2dist(tree)

By default the phy2dist() argument precompute_dist is TRUE, such that a pairwise distance matrix is calculated automatically and is stored in d@distance. phy2dist() cannot work without this matrix. For more than 10,000 species it gives an error unless precompute_dist is set to TRUE.

  1. Convert the distance object to similarity object (by means of a linear or exponential transform) using the dist2sim() function:
s <- dist2sim(d, "linear")
  1. Generate a metacommunity object using the metacommunity() function
meta <- metacommunity(partition, s)
  1. Calculate diversity
meta_gamma(meta, 0:2)
##                div_type measure q type_level type_name partition_level
## 1 Phylogenetic Distance   Gamma 0      types             metacommunity
## 2 Phylogenetic Distance   Gamma 1      types             metacommunity
## 3 Phylogenetic Distance   Gamma 2      types             metacommunity
##   partition_name diversity transformation normalised k    max_d
## 1                 2.359989         linear       TRUE 1 3.029122
## 2                 2.348281         linear       TRUE 1 3.029122
## 3                 2.336555         linear       TRUE 1 3.029122

Branch-based phylogenetic diversity

  1. Initialise data:
tree <- ape::rtree(4)
partition <- matrix(1:12, ncol = 3)
partition <- partition / sum(partition)
colnames(partition) <- letters[1:3]
row.names(partition) <- paste0("sp", 1:4)
tree$tip.label <- row.names(partition)
  1. Generate a similarity object using the phy2branch() function
s <- phy2branch(tree, partition)
  1. Generate a metacommunity object using the metacommunity() function
meta <- metacommunity(partition, s)
  1. Calculate diversity
meta_gamma(meta, 0:2)
##              div_type measure q type_level type_name partition_level
## 1 Phylogenetic Branch   Gamma 0      types             metacommunity
## 2 Phylogenetic Branch   Gamma 1      types             metacommunity
## 3 Phylogenetic Branch   Gamma 2      types             metacommunity
##   partition_name diversity transformation normalised  k max_d
## 1                 2.604889             NA         NA NA    NA
## 2                 2.428740             NA         NA NA    NA
## 3                 2.279777             NA         NA NA    NA

Note that: a metacommunity that was generated using this approach will contain three additional slots:

Genetic diversity

  1. Initialise data: Note: the package pinfsc50 must be installed for this example to work.
library(rdiversity)
vcf_file <- system.file("extdata", "pinf_sc50.vcf.gz", package = "pinfsc50")
# read in twice: first for the column names then for the data
tmp_vcf <- readLines(vcf_file)
vcf_data <- read.table(vcf_file, stringsAsFactors = FALSE)
# filter for the columns names
vcf_names <- unlist(strsplit(tmp_vcf[grep("#CHROM", tmp_vcf)], "\t"))
names(vcf_data) <- vcf_names
partition <- cbind.data.frame(A = c(rep(1, 9), rep(0, 9)), B = c(rep(0, 9), rep(1, 9)))
partition <- partition / sum(partition)
  1. Generate a distance matrix using the gen2dist() function:
d <- gen2dist(vcf)
  1. Convert the distance object to a similarity object (by means of a linear or exponential transform) using the dist2sim() function:
s <- dist2sim(d, transform = "l")

Note: the dist2sim() function contains an optional argument, max_d, which defines the distance at which pairs of individuals have similarity zero. If not supplied this is set to the maximum distance observed in the distance matrix. If comparing different windows on a genome, for example, it is necessary to ensure max_d is the same for each analysis.

  1. Generate a metacommunity object using the metacommunity() function:
rownames(partition) <- rownames(s@similarity)
meta <- metacommunity(partition, s)
  1. Calculate diversity, for example beta diversity measures are used to identify trends such as differentiation:
norm_meta_beta(meta, 0:2)

User defined distance

partition <- matrix(sample(6), nrow = 3)
rownames(partition) <- paste0("sp", 1:3)
partition <- partition / sum(partition)

d <- matrix(c(0, .75, 1, .75, 0, .3, 1, .3, 0), nrow = 3)
rownames(d) <- paste0("sp", 1:3)
colnames(d) <- paste0("sp", 1:3)
d <- distance(d, "my_taxonomy")
s <- dist2sim(d, "linear")

meta <- metacommunity(partition, s)

User defined similarity

partition <- matrix(sample(6), nrow = 3)
rownames(partition) <- paste0("sp", 1:3)
partition <- partition / sum(partition)

s <- matrix(c(1, .8, 0, .8, 1, .1, 0, .1, 1), nrow = 3)
rownames(s) <- paste0("sp", 1:3)
colnames(s) <- paste0("sp", 1:3)
s <- similarity(s, "my_functional")

meta <- metacommunity(partition, s)

Additional tools

repartition()

This example needs the ape package too.

tree <- ape::rtree(5)
tree$tip.label <- paste0("sp", 1:5)

partition <- matrix(rep(1, 10), nrow = 5)
row.names(partition) <- paste0("sp", 1:5)
partition <- partition / sum(partition)
s <- phy2branch(tree, partition)
meta <- metacommunity(partition, s)

new_partition <- matrix(sample(10), nrow = 5)
row.names(new_partition) <- paste0("sp", 1:5)
new_partition <- new_partition / sum(new_partition)

new_meta <- repartition(meta, new_partition)