Introduction to ecodive

Introduction

Ecodive covers an ecological diversity analysis from start to finish:

  • Alpha diversity metrics describe a single sample’s diversity.
  • Beta diversity metrics indicate how different a pair of samples are from each other.
  • Ordinations place samples on a few axes, so that similar samples plot near each other.
  • Statistical tests check whether a variable, such as treatment or body site, explains the differences between samples.

In this guide, we’ll use the ex_counts dataset included with ecodive. ex_counts is a feature table that enumerates how many times each bacterial genera was observed on different body sites.

library(ecodive)

t(ex_counts)
#>                   Saliva Gums Nose Stool
#> Streptococcus        162  793   22     1
#> Bacteroides            2    4    2   611
#> Corynebacterium        0    0  498     1
#> Haemophilus          180   87    2     1
#> Propionibacterium      1    1  251     0
#> Staphylococcus         0    1  236     1

In this example, the ‘features’ in our feature table are genera. However, your own dataset can use whatever feature makes sense - species, OTUs, ASVs, or even something completely unrelated to ecology.

Alpha Diversity

Alpha diversity metrics describe how many different genera are present in a sample. Depending on the metric, this can take into account the number of unique genera (richness), how evenly the population is split among genera (evenness), or how distantly related the genera are (phylogenetic diversity).

The available alpha diversity metrics can be listed using list_metrics().

list_metrics('alpha')[,1:5]
#>                                        name                id phylo weighted int_only
#> 1  Abundance-based Coverage Estimator (ACE)               ace FALSE     TRUE     TRUE
#> 3                       Berger-Parker Index            berger FALSE     TRUE    FALSE
#> 6                           Brillouin Index         brillouin FALSE     TRUE     TRUE
#> 8                                     Chao1             chao1 FALSE     TRUE     TRUE
#> 15           Faith's Phylogenetic Diversity             faith  TRUE    FALSE    FALSE
#> 16                           Fisher's Alpha            fisher FALSE     TRUE     TRUE
#> 18                               Gini Index              gini FALSE     TRUE    FALSE
#> 19                       Gini-Simpson Index           simpson FALSE     TRUE    FALSE
#> 20                          Good's Coverage    goods_coverage FALSE     TRUE     TRUE
#> 23                          Heip's Evenness              heip FALSE     TRUE    FALSE
#> 25                              Hill Number              hill FALSE     TRUE    FALSE
#> 27                    Inverse Simpson Index       inv_simpson FALSE     TRUE    FALSE
#> 33                Margalef's Richness Index          margalef FALSE     TRUE     TRUE
#> 35                           McIntosh Index          mcintosh FALSE     TRUE     TRUE
#> 36                      McIntosh's Evenness mcintosh_evenness FALSE     TRUE     TRUE
#> 37               Menhinick's Richness Index         menhinick FALSE     TRUE     TRUE
#> 42                        Observed Features          observed FALSE    FALSE    FALSE
#> 45                        Pielou's Evenness            pielou FALSE     TRUE    FALSE
#> 48                            Renyi Entropy             renyi FALSE     TRUE    FALSE
#> 49                  Shannon Diversity Index           shannon FALSE     TRUE    FALSE
#> 50                Simpson's Dominance Index         dominance FALSE     TRUE    FALSE
#> 51                       Simpson's Evenness  simpson_evenness FALSE     TRUE    FALSE
#> 56               Squares Richness Estimator           squares FALSE     TRUE     TRUE
#> 57                 Strong's Dominance Index            strong FALSE     TRUE    FALSE
#> 59                          Tsallis Entropy           tsallis FALSE     TRUE    FALSE
  • Further reading: vignette('adiv')

Beta Diversity

Beta diversity metrics describe how different two samples are, based on the genera observed in each. UniFrac metrics incorporate a phylogenetic tree into this calculation.

The available beta diversity metrics can be listed using list_metrics().

list_metrics('beta')[,2:6]
#>                           id phylo weighted int_only true_metric
#> 2                  aitchison FALSE     TRUE    FALSE        TRUE
#> 4              bhattacharyya FALSE     TRUE    FALSE        TRUE
#> 5                       bray FALSE     TRUE    FALSE       FALSE
#> 7                   canberra FALSE     TRUE    FALSE        TRUE
#> 9                  chebyshev FALSE     TRUE    FALSE        TRUE
#> 10                     chord FALSE     TRUE    FALSE        TRUE
#> 11                     clark FALSE     TRUE    FALSE        TRUE
#> 12                  sorensen FALSE    FALSE    FALSE       FALSE
#> 13                divergence FALSE     TRUE    FALSE        TRUE
#> 14                 euclidean FALSE     TRUE    FALSE        TRUE
#> 17       generalized_unifrac  TRUE     TRUE    FALSE        TRUE
#> 19                     gower FALSE     TRUE    FALSE        TRUE
#> 20                   hamming FALSE    FALSE    FALSE        TRUE
#> 21                 hellinger FALSE     TRUE    FALSE        TRUE
#> 22                      horn FALSE     TRUE    FALSE       FALSE
#> 24                   jaccard FALSE    FALSE    FALSE        TRUE
#> 25                    jensen FALSE     TRUE    FALSE        TRUE
#> 26                       jsd FALSE     TRUE    FALSE        TRUE
#> 27                lorentzian FALSE     TRUE    FALSE       FALSE
#> 28                 manhattan FALSE     TRUE    FALSE        TRUE
#> 30                  matusita FALSE     TRUE    FALSE        TRUE
#> 33                 minkowski FALSE     TRUE    FALSE        TRUE
#> 34                  morisita FALSE     TRUE     TRUE       FALSE
#> 35                    motyka FALSE     TRUE    FALSE       FALSE
#> 36        normalized_unifrac  TRUE     TRUE    FALSE        TRUE
#> 38                    ochiai FALSE    FALSE    FALSE       FALSE
#> 39            philr_distance  TRUE     TRUE    FALSE        TRUE
#> 40                psym_chisq FALSE     TRUE    FALSE       FALSE
#> 41          robust_aitchison FALSE     TRUE    FALSE       FALSE
#> 43                   soergel FALSE     TRUE    FALSE        TRUE
#> 44             squared_chisq FALSE     TRUE    FALSE       FALSE
#> 45             squared_chord FALSE     TRUE    FALSE       FALSE
#> 46         squared_euclidean FALSE     TRUE    FALSE       FALSE
#> 48                    topsoe FALSE     TRUE    FALSE        TRUE
#> 49        unweighted_unifrac  TRUE    FALSE    FALSE        TRUE
#> 50 variance_adjusted_unifrac  TRUE     TRUE    FALSE        TRUE
#> 51               wave_hedges FALSE     TRUE    FALSE       FALSE
#> 52          weighted_unifrac  TRUE     TRUE    FALSE        TRUE

Example

Rarefaction

The ex_counts feature table has 345 saliva observations, but nose has 1011 observations. This unequal sampling depth can cause systematic biases. Specifically, rare genera will be observed more often in samples with greater sampling depths, thereby artificially inflating the observed richness.

The first step then is to rarefy ex_counts so that all samples have the same number of observations. Rarefying randomly removes observations from samples with more observations.

rowSums(ex_counts)
#> Saliva   Gums   Nose  Stool 
#>    345    886   1011    615 

counts <- rarefy(ex_counts)

rowSums(counts)
#> Saliva   Gums   Nose  Stool 
#>    345    345    345    345 

t(counts)
#>                   Saliva Gums Nose Stool
#> Streptococcus        162  309    6     1
#> Bacteroides            2    2    0   341
#> Corynebacterium        0    0  171     1
#> Haemophilus          180   34    0     1
#> Propionibacterium      1    0   82     0
#> Staphylococcus         0    0   86     1

Classic Metrics

These alpha and beta diversity metrics have been around for 50+ years and don’t require a phylogenetic tree. The beta diversity functions can take a weighted = FALSE argument to use only presence/absence information instead of relative abundances.

## Alpha Diversity -------------------

shannon(counts)
#>     Saliva       Gums       Nose      Stool 
#> 0.74119910 0.35692121 1.10615349 0.07927797 


## Beta Diversity --------------------

bray(counts)
#>          Saliva      Gums      Nose
#> Gums  0.4260870                    
#> Nose  0.9797101 0.9826087          
#> Stool 0.9884058 0.9884058 0.9913043

Phylogenetic Metrics

A phylogenetic tree enables alpha and beta diversity metrics to take into account evolutionary relatedness between the observed genera, generally giving higher diversity values for samples with more distantly related genera. Faith (for alpha diversity) and UniFrac (for beta diversity) are examples of phylogenetic metrics.

The ex_tree object included with ecodive provides the phylogenetic tree for the genera in ex_counts. For your own datasets, you can use ecodive’s read_tree() function to import a phylogenetic tree from a newick formatted string or file.

## Alpha Diversity -------------------

faith(counts, tree = ex_tree)
#> Saliva   Gums   Nose  Stool 
#>    180    155    101    202 


## Beta Diversity --------------------

normalized_unifrac(counts, tree = ex_tree)
#>          Saliva      Gums      Nose
#> Gums  0.4328662                    
#> Nose  0.7928701 0.6767840          
#> Stool 0.9677535 0.9829736 0.9936121

Distance Matrices

Beta diversity functions return a dist object. You can convert this to a standard R matrix with the as.matrix() function.

dm <- bray(counts)
dm
#>          Saliva      Gums      Nose
#> Gums  0.1428571                    
#> Nose  0.5000000 0.7142857          
#> Stool 0.3333333 0.2500000 0.3333333

mtx <- as.matrix(dm)
mtx
#>           Saliva      Gums      Nose     Stool
#> Saliva 0.0000000 0.1428571 0.5000000 0.3333333
#> Gums   0.1428571 0.0000000 0.7142857 0.2500000
#> Nose   0.5000000 0.7142857 0.0000000 0.3333333
#> Stool  0.3333333 0.2500000 0.3333333 0.0000000

mtx['Saliva', 'Nose']
#> [1] 0.5

Ordination

An ordination turns a distance matrix into coordinates for a plot. ecodive has nine methods that take distances, run by name with dist_ord() or directly by their own functions, and eight (pca(), rpca(), rda(), cca(), ca(), lda(), plsda() and oplsda()) that take the count table itself, run by name with count_ord().

Function Method
pcoa() Principal Coordinates Analysis (PCoA)
mds() Metric Multidimensional Scaling
nmds() Non-metric Multidimensional Scaling (NMDS)
isomap() Isometric Feature Mapping (Isomap)
tsne() t-distributed Stochastic Neighbor Embedding
umap() Uniform Manifold Approximation and Projection
dbrda() Distance-based Redundancy Analysis (db-RDA)
capscale() Constrained Analysis of Principal Coordinates
capda() Discriminant Canonical Analysis of Principal Coordinates (CAP)
pca() Principal Component Analysis (PCA)
rpca() Robust Aitchison PCA
rda() Redundancy Analysis (RDA)
cca() Canonical Correspondence Analysis (CCA)
ca() Correspondence Analysis (CA)
lda() Linear Discriminant Analysis (LDA)
plsda() Partial Least Squares Discriminant Analysis
oplsda() Orthogonal PLS Discriminant Analysis (OPLS-DA)

pcoa_biplot() and envfit() add arrows for the features or metadata that drive the axes. procrustes() and procrustes_test() compare two ordinations of the same samples. varpart() splits the variation that two to four sets of metadata explain into the parts each explains alone and the parts they share, and forward_select() picks the variables worth keeping first.

Four samples are too few to ordinate, so this example uses R’s built-in iris data: 150 flowers, four measurements each, and three species. Every ordination returns a matrix with one row per sample and one column per axis.

dm  <- bray(iris[, 1:4])
ord <- pcoa(dm)

head(ord, 3)
#>          PCoA1       PCoA2        PCoA3
#> [1,] 0.1692812 -0.02591990 -0.005053611
#> [2,] 0.1706354  0.02346821  0.030848760
#> [3,] 0.1870090 -0.00320247  0.032221661

# Percent of variance on each axis.
round(100 * attr(ord, 'prop'), 1)
#> [1] 89.0  9.3  2.9

# Colored by a column of metadata, with a legend; the title and axis
# labels come from the result.
plot(ord, 'Species', iris)

plot() draws any of ecodive’s results from what it already holds: ordinations with their loadings, constraints and centroids, the permutation distributions of tests, and the results of envfit(), simper(), varpart(), dirmult_ttest() and the rest.

  • Further reading: vignette('ordination')

Statistical Tests

ecodive’s permutation tests take the same distance matrix, and a variable to test: a vector with one value per sample, or a column of a data frame.

Function Test
permanova() Permutational Multivariate Analysis of Variance
permdisp() Homogeneity of Multivariate Dispersions
anosim() Analysis of Similarities
mrpp() Multi-Response Permutation Procedure
mantel() Mantel Test
mantel_partial() Partial Mantel Test

dist_test() runs any of them by name.

permanova(dm, 'Species', iris)
#> Permutational multivariate analysis of variance (PERMANOVA)
#> 
#> F = 532.7, p = 0.001, z = 577.6
#> Permutations: 999 (free)
#> 
#> Model R2 = 0.8788. Model tested as a whole:
#> 
#>           Df SumOfSqs     R2     F Pr(>F)    
#> Model      2   2.3173 0.8788 532.7  0.001 ***
#> Residual 147   0.3197 0.1212                 
#> Total    149   2.6370 1.0000                 
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
  • Further reading: vignette('stat_tests')

Performance with Large Datasets

ecodive is designed to be fast out-of-the-box. However, if you are working with very large datasets (e.g., thousands of samples), you can gain additional performance by following the recommendations in our performance guide.

  • Further reading: vignette('performance')