28 Multivariate hypothesis testing
So far we have explored two categories of multivariate analysis methods: clustering and ordination. These techniques are mainly for data exploration and visualization. But there are also methods for testing multivariate hypotheses that feel like extensions of univariate tests we have already seen.
Many multivariate hypothesis tests address the same kinds of scientific questions as familiar univariate tests. The main difference is that they operate on multiple response variables or on matrices of pairwise distances rather than a single response variable. The methods in this table are conceptually analogous, but they are not necessarily mathematically equivalent or based on the same statistical assumptions.
| Univariate method | Univariate question | Multivariate analogue | Multivariate question |
|---|---|---|---|
| t-test | Do two groups differ in their means? | Hotelling’s \(T^2\) | Do two groups differ in their multivariate means? |
| ANOVA | Do groups differ in their means? | MANOVA / PERMANOVA | Do groups differ in their multivariate means or composition? |
| Kruskal–Wallis test | Do groups differ in their distributions, as assessed using ranks? | ANOSIM | Are distances between groups generally greater than distances within groups? |
| Levene’s test | Do groups differ in their variances? | PERMDISP (betadisper) |
Do groups differ in their multivariate dispersions? |
| Pearson correlation | Are two continuous variables correlated? | Mantel test | Are two distance matrices correlated? |
| Partial correlation | Are two variables correlated after accounting for a third? | Partial Mantel test | Are two distance matrices correlated after accounting for a third distance matrix? |
| Multiple linear regression | How does a response depend on multiple predictors? | MRM | How does pairwise dissimilarity depend on multiple predictor distance matrices? |
| Multiple linear regression | How does a response depend on several predictors? | RDA / dbRDA | How does multivariate composition depend on environmental or other predictors? |
| ANCOVA / factorial ANOVA | How do multiple predictors and their interactions affect a response? | PERMANOVA with multiple predictors | How do multiple predictors and their interactions explain multivariate differences? |
| Linear mixed-effects model | How does a response depend on predictors while accounting for grouped observations? | MLPE | How do pairwise dissimilarities depend on predictors while accounting for shared samples or populations? |
28.1 Comparing groups
We can test for differences between groups in multivariate using analogues of ANOVA: multivariate analysis of variance (MANOVA) and permutational multivariate analysis of variance (PERMANOVA). Multivariate analysis of variance (MANOVA) is an extension of ANOVA with multiple response variables. The underlying theory and linear algebra is very similar to ANOVA, and so many of the same assumptions apply (just in many dimensions instead of one). For that reason, MANOVA is often not appropriate for real biological data without careful experimental design and exploratory data analysis to confirm that the test’s assumptions are met.
28.1.1 PERMANOVA
Permutational analysis of variance (PERMANOVA) is a nonparametric version of MANOVA (Anderson 2001). It is nonparametric because it uses random shuffling, or permutation, of group membership to determine statistical significance instead of calculating an F statistic based on probability theory. The most common R function for PERMANOVA is adonis2() from the vegan package.
28.1.1.1 Permutation tests
A permutation test is one that assesses statistical significance using random shuffling, or permutation, of the data. The idea is that if some response variable depends on group membership, then shuffling the observations so that group memberships randomly change should break that dependence. Consider Figure 28.1 below. Group A in grey tends to have smaller values. A t-test confirms this (t=-5.69, 34.22 d.f., P < 0.01).
But look what happens to the test statistic t if we permute the group memberships (Figure 28.2). Recall that t summarizes the difference in group means. So, a t with a smaller absolute value means that the group means are less different than they were originally.
After permutation, the summary of the difference in group means is much smaller (0.04). Let’s repeat this a bunch of times:
We can obtain a permutation test by repeating this process many times and comparing the test statistic in the original dataset to the distribution of test statistics in the permuted datasets.
The distribution of t statistics of the permuted datasets tells us what t values we could expect if there was no difference in mean value between groups A and B. In other words, it is the distribution of the test statistic under the null hypothesis. But unlike in a traditional t-test where we define the reference distribution from the number of degrees of freedom in the dataset–i.e., we make assumptions about the distribution of t–in this permutation test we let the dataset define the distribution of t. In this test, none of the permuted t are as extreme as the original t, so the P-value is “<0.001” (because P can never be 0).
The basic idea behind PERMANOVA is the same as this permutational t-test we just performed, only with a multivariate distance matrix rather than differences in menas.
28.1.1.2 Example with NEON data
Let’s revisit the NEON small mammal measurement data. We analyzed this dataset previously in Section 27.2.3. Download the individual measurement dataset and the taxonomic dataset and put them in your working directory.
tax <- read.csv("data-neon-taxa.csv")
ind <- read.csv("data-neon-ind-meas.csv")Let’s use PERMANOVA to test for a difference between four genera of morphologically similar mice: Peromyscus, Onychomys, Reithrodontomys, and Mus. The first three are North American species in family Cricetidae, while Mus is a Eurasian genus in family Muridae. We ordinated their morphology using the standard measurements (total length, tail length, hindfoot length, and ear length) using PCA in Section 27.2.3. First, filter the data to those species, and to only those individuals who are not missing any measurements. We will not adjust for size, because differences in size are a meaningful part of the variation between these species.
use.genera <- c("Mus", "Onychomys",
"Peromyscus", "Reithrodontomys")
use.abb <- tax$abb[tax$genus %in% use.genera]
dx <- ind[ind$abb %in% use.abb,]
use.cols <- c("abb", "totalLength",
"tailLength", "hindfootLength",
"earLength")
dx <- dx[,use.cols]
# only want individuals with no missing measurements
dx <- dx[complete.cases(dx),]
# identify genera
dx$genus <- tax$genus[match(dx$abb, tax$abb)]
# add some colors and shapes
cols <- hcl.colors(length(use.genera), palette="Dark 3")
pchs <- 15:18
names(cols) <- use.genera
names(pchs) <- use.genera
dx$color <- cols[dx$genus]
dx$pch <- pchs[dx$genus]
# don't do this in a real research project:
# cut down the dataset to randomly select at
# at least 100 mice in each genus
# permanova takes way too long with >5000 samples
set.seed(1776)
subset.list <- vector("list", length=4)
for(i in 1:4){
irows <- which(dx$genus == use.genera[i])
keep.rows <- sample(irows, 100, replace=FALSE)
subset.list[[i]] <- dx[keep.rows,]
}
dx <- do.call(rbind, subset.list)Let’s visualize the data first. We can use PCA as we did in Section 27.2.3. We will need to standardize the data before PCA. We will also use the standardized data in the PERMANOVA.
library(vegan)
meas.cols <- c("totalLength", "tailLength",
"hindfootLength", "earLength")
ymatrix <- dx[,meas.cols]
ymatrix.sc <- scale(ymatrix)
p1 <- pca(ymatrix.sc)
summary(p1)
Call:
pca(X = ymatrix.sc)
Partitioning of variance:
Inertia Proportion
Total 4 1
Unconstrained 4 1
Eigenvalues, and their contribution to the variance
Importance of components:
PC1 PC2 PC3 PC4
Eigenvalue 2.4097 1.0547 0.32766 0.20794
Proportion Explained 0.6024 0.2637 0.08191 0.05198
Cumulative Proportion 0.6024 0.8661 0.94802 1.00000
Extract the scores and build the plot:
xy <- scores(p1, display="sites", choices=1:2, scaling=1)
par(mar=c(5,5,1,1))
plot(xy[,1], xy[,2],
xlab="PC1 (61.5$)", ylab="PC2 (27.4%)",
pch=dx$pch, col=dx$col)
legend("topleft", legend=use.genera,
pch=pchs, col=cols, cex=1.2,
bty="n", text.font=3)
The PCA suggests that Peromyscus and Onychomys are morphologically distinct from Reithrodontomys and Mus, and that Reithrodontomys and Mus are not morphologically distinct from each other. We can test whether these visual interpretations are supported by the data with PERMANOVA. But first, we need to check for homogeneity of multivariate variance between the groups. This is one of the assumptions of PERMANOVA. The most common method is called a beta dispersion test and is available in vegan as betadisper(). It tests whether the groups have the same within-group variance, measured as mean distance to centroid.
d <- vegdist(ymatrix.sc, method="euclidean")
beta.disp.test <- betadisper(d, dx$genus)
permutest(beta.disp.test)
Permutation test for homogeneity of multivariate dispersions
Permutation: free
Number of permutations: 999
Response: Distances
Df Sum Sq Mean Sq F N.Perm Pr(>F)
Groups 3 7.387 2.46229 5.6949 999 0.003 **
Residuals 396 171.216 0.43236
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
The test was significant, which is evidence that some of the genera differ in their within group dispersion. We can inspect the dispersions by looking at the betadisper() object.
beta.disp.test
Homogeneity of multivariate dispersions
Call: betadisper(d = d, group = dx$genus)
No. of Positive Eigenvalues: 4
No. of Negative Eigenvalues: 0
Average distance to median:
Mus Onychomys Peromyscus Reithrodontomys
0.9892 1.0064 1.3302 1.1001
Eigenvalues for PCoA axes:
PCoA1 PCoA2 PCoA3 PCoA4
961.46 420.84 130.74 82.97
The important part of this output is the Average distance to median. Peromyscus has the largest within-group dispersion, and Mus the least. Reithrodontomys has the second most, and Onychomys slightly less. This makes biological sense: our dataset includes 13 species of Peromyscus, 4 of Reithrodontomys, 3 of Onychomys, and 1 of Mus. You can check this with table(substr(use.abb, 1, 3)).
The beta dispersion test tells us that we are measuring two sources of morphological variation within each genus: variation among species and variation among individuals within species. A genus represented by 13 species has more opportunities to encompass substantial morphological diversity than one represented by a single species, although species richness alone doesn’t guarantee greater dispersion. The take home here is that PERMANOVA and the multivariate dispersion test need to be interpreted together.
The vegan function for PERMANOVA is adonis2(). We will use it on the scaled version of the measurement dataset, the same as we used for the beta dispersion test.
set.seed(999)
mod1 <- adonis2(ymatrix.sc ~ genus, data=dx,
method="euclidean")
mod1Permutation test for adonis under reduced model
Permutation: free
Number of permutations: 999
adonis2(formula = ymatrix.sc ~ genus, data = dx, method = "euclidean")
Df SumOfSqs R2 F Pr(>F)
Model 3 934.24 0.58537 186.35 0.001 ***
Residual 396 661.76 0.41463
Total 399 1596.00 1.00000
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Here are the important parts of the output:
- Pseudo-\(F_{3,396}=186.4, p = 0.001\). This means that there were statistically significant morphological differences among the four genera.
- \(R^2=0.59\) means that genus explains about 59% of the variation in morphology in the samples.
- Residual \(R^2=0.41\) means that about 41% of the variation unexplained.
This PERMANOVA result is substantial, while the dispersion test demonstrates that the genera differ in their morphological variability. The differences in within-genus dispersion are biologically plausible because the genera contain different numbers of species.
The PERMANOVA we just did was an omnibus test, just as the initial test with aov() is for ANOVA (Section 15.5.1.1). For ANOVA, we then use a post hoc Tukey test to check for significant pairwise differences. For PERMANOVA, the usual post hoc test is a series of pairwise PERMANOVAs. We can fit these in a loop.
set.seed(1701)
# define pairwise combinations
combos <- combn(use.genera, 2)
ncombos <- ncol(combos)
# data frame to catch results
res <- data.frame(
genus1=combos[1,],
genus2=combos[2,],
Fstat=NA,
R2=NA,
p=NA)
# run pairwise combinations in a loop
for(i in 1:ncombos){
use.rows <- dx$genus %in% combos[,i]
idata <- ymatrix.sc[use.rows,]
igenus <- dx[use.rows,]
imod <- adonis2(idata~genus, data=igenus,
method="euclidean")
res$Fstat[i] <- imod$F[1]
res$R2[i] <- imod$R2[1]
res$p[i] <- imod$`Pr(>F)`[1]
}
res genus1 genus2 Fstat R2 p
1 Mus Onychomys 194.050391 0.49496288 0.001
2 Mus Peromyscus 249.969637 0.55800576 0.001
3 Mus Reithrodontomys 5.392538 0.02651296 0.001
4 Onychomys Peromyscus 234.424137 0.54211622 0.001
5 Onychomys Reithrodontomys 150.989668 0.43264796 0.001
6 Peromyscus Reithrodontomys 232.377973 0.53993928 0.001
All of the pairwise tests use 1 and 198 degrees of freedom for their pseudo-F statistics. Before we interpret these P-values, we need to apply a correction for multiple comparisions. This will control the family-wise error rate. We will use a Holm correction.
res$p.adj <- p.adjust(res$p, method="holm")
res genus1 genus2 Fstat R2 p p.adj
1 Mus Onychomys 194.050391 0.49496288 0.001 0.006
2 Mus Peromyscus 249.969637 0.55800576 0.001 0.006
3 Mus Reithrodontomys 5.392538 0.02651296 0.001 0.006
4 Onychomys Peromyscus 234.424137 0.54211622 0.001 0.006
5 Onychomys Reithrodontomys 150.989668 0.43264796 0.001 0.006
6 Peromyscus Reithrodontomys 232.377973 0.53993928 0.001 0.006
The adjusted P-values confirm our initial suspicion based on Figure 28.5: that the genera differ from each other morphological. However, the difference between Reithrodontomys and Mus was much smaller than the differences between the other genera, as shown by the much smaller \(R^2\) for that comparison. Let’s add some ellipses to the PCA for better visualization:
# get centroids
centx <- tapply(xy[,1], dx$genus, mean)
centy <- tapply(xy[,2], dx$genus, mean)
par(mar=c(5,5,1,1))
plot(xy[,1], xy[,2],
xlab="PC1 (61.5%)", ylab="PC2 (27.4%)",
pch=dx$pch, col=dx$col)
ordiellipse(xy, dx$genus, #kind="se",
draw="polygon", col=cols)
text(centx, centy, use.genera, font=4, cex=1.2)
legend("topleft", legend=use.genera,
pch=pchs, col=cols, cex=1.2,
bty="n", text.font=3)
28.1.2 ANOSIM
Analysis of similarities (ANOSIM) is a permutation-based test that, like PERMANOVA, evaluates differences in multivariate composition among predefined groups. Rather than partitioning variation among and within groups, ANOSIM compares the ranks of pairwise distances within groups to those between groups. Its test statistic, (R), ranges from −1 to +1, with positive values indicating that observations from different groups tend to be more dissimilar than observations within the same group. ANOSIM can be particularly sensitive to differences in multivariate dispersion, so significant results do not necessarily indicate differences in group locations.
Example coming soon!
28.2 Analyzing dissimilarity
PERMANOVA is a way to compare groups of observations in a multivariate space. Another way of understanding multivariate patterns is to explore relationships between distance matrices. Consider Figure 28.7 below. It shows how dissimilarity between samples in terms of one set of variables is related to dissimilarity in terms of another. In this example, sites that are more dissimilar in terms of their soil chemistry are also more dissimilar in terms of their plant communities. Each point on the figure represents a pair of observations, not a single observations.
When we test for a correlation between distance metrics, we perform a Mantel test. There are also regression approaches for dissimilarities such as ANOSIM and multiple regression on distance matrices (MRM) and maximum likelihood population effects (MLPE).
28.2.1 Mantel tests
For an example Mantel test, let’s revisit the small mammal capture data from Section 26.2.2 and Section 27.5.4. Download the site-level capture dataset, the site metadata, and the taxonomic dataset and put them in your working directory.
tax <- read.csv("data-neon-taxa.csv")
cap <- read.csv("data-neon-captures-site.csv")
met <- read.csv("data-neon-metadata-site.csv")As before, convert the capture numbers to a binary presence-absence, and remove a species that is present at no sites.
pa <- cap
# fix some columns and set rownames
pa$X <- NULL
rownames(pa) <- pa$site
pa$site <- NULL
# convert capture numbers to presence absence
pa[pa>0] <- 1
# leaves 133 species
pa <- pa[,-which(colSums(pa)==0)]We will compare dissimilarity in terms of small mammal species composition with geographic distance. Notice that we cannot calculate geographic distance using raw latitude and longitude because that would ignore the curvature of the Earth. We will use package terra to calculate distances across the famously non-flat Earth’s surface.
library(terra)
coords <- met[,c("lat", "lon")]
# convert coordinates to spatial points (WGS84)
sites <- vect(coords, geom=c("lon", "lat"), crs="EPSG:4326")
# calculate geographic distance matrix in meters
geo.dist <- terra::distance(sites)
# convert to km
geo.dist <- as.dist(geo.dist / 1000)Now we can calculate the Sørensen distance matrix using the species presences in pa and run the Mantel test.
mamm.dist <- vegdist(pa)
mantel(geo.dist, mamm.dist)
Mantel statistic based on Pearson's product-moment correlation
Call:
mantel(xdis = geo.dist, ydis = mamm.dist)
Mantel statistic r: 0.599
Significance: 0.001
Upper quantiles of permutations (null model):
90% 95% 97.5% 99%
0.0826 0.0999 0.1198 0.1425
Permutation: free
Number of permutations: 999
The Mantel r is 0.599, which is a moderately strong correlation. We can visualize this by plotting the distance matrices.
par(mar=c(5,5,1,1))
plot(geo.dist, mamm.dist,
xlab="Geographic distance (km)",
ylab="Small mammal dissimilarity (unitless)")
Just as in Figure 27.29, many of the pairs are made of sites that share no species and thus have the maximal Sørensen dissimilarity of 1. This explains the stripe of points along the top of the plot. The shape of the plot suggests that the nonlinear rank-based Mantel test may be more appropriate.
mantel(geo.dist, mamm.dist, method="spearman")
Mantel statistic based on Spearman's rank correlation rho
Call:
mantel(xdis = geo.dist, ydis = mamm.dist, method = "spearman")
Mantel statistic r: 0.6805
Significance: 0.001
Upper quantiles of permutations (null model):
90% 95% 97.5% 99%
0.0806 0.1107 0.1410 0.1666
Permutation: free
Number of permutations: 999
The rank-based Mantel \(\rho\) is greater than the linear Mantel r.
28.2.2 Partial Mantel tests
A partial Mantel test extends the Mantel test
# Select environmental variables
env <- met[, c("elev", "precip", "temp", "npp",
"seas.pre", "seas.temp")]
# Standardize and calculate environmental distances
env.dist <- dist(scale(env))The initial Mantel test tested whether sites that are geographically farther apart are more dissimilar in terms of their mammal species composition. This partial Mantel test will test whether sites that are more environmentally different are more dissimilar in terms of species composition after accounting for geographic distance.
set.seed(123)
mantel.partial(mamm.dist, env.dist, geo.dist,
method="pearson", permutations=999)
Partial Mantel statistic based on Pearson's product-moment correlation
Call:
mantel.partial(xdis = mamm.dist, ydis = env.dist, zdis = geo.dist, method = "pearson", permutations = 999)
Mantel statistic r: 0.5004
Significance: 0.001
Upper quantiles of permutations (null model):
90% 95% 97.5% 99%
0.0725 0.0912 0.1090 0.1307
Permutation: free
Number of permutations: 999
In vegan::mantel.partial(), the first two arguments are the distance matrices whose correlation you’re testing, and the third is the distance matrix you’re controlling for. In our example, we tested whether dissimilarity in terms of mammal community composition is correlated with dissimilarity in terms of environmental variables, after accounting for geographic distance. If we reverse the second and third arguments, we get a different test:
set.seed(123)
mantel.partial(mamm.dist, geo.dist, env.dist,
method="pearson", permutations=999)
Partial Mantel statistic based on Pearson's product-moment correlation
Call:
mantel.partial(xdis = mamm.dist, ydis = geo.dist, zdis = env.dist, method = "pearson", permutations = 999)
Mantel statistic r: 0.2522
Significance: 0.001
Upper quantiles of permutations (null model):
90% 95% 97.5% 99%
0.0764 0.1028 0.1218 0.1439
Permutation: free
Number of permutations: 999
The second test looks for correlations between mammal community composition and geographic distance, after accounting for environmental differences. Notice that the Mantel r statistic is much smaller.
We can plot the partial correlation just as we can an ordinary Mantel correlation.
man02 <- mantel.partial(mamm.dist,
env.dist,
geo.dist)
# Extract pairwise distances
m <- as.vector(mamm.dist)
e <- as.vector(env.dist)
g <- as.vector(geo.dist)
# Remove the linear association with geographic distance
m.res <- resid(lm(m ~ g))
e.res <- resid(lm(e ~ g))
# Plot the partial relationship
par(mar=c(5,5,1,1))
plot(e.res, m.res,
pch = 1,
xlab = "Environmental dissimilarity (adjusted for geography)",
ylab = "Mammal dissimilarity (adjusted for geography)")
abline(lm(m.res ~ e.res), col = "red", lwd = 2)
It is important to note that partial Mantel tests can have unreliable Type I error rates with spatially autocorrelated data, so the significant results here warrant caution. In this case, dissimilarity in environmental characteristics and dissimilarity of mammal community composition are likely both spatially autocorrelated. For formal inference about environmental effects on community composition after accounting for space, distance-based redundancy analysis (dbRDA) with spatial predictors is often a better-supported alternative.
28.2.3 Multiple regression on distance matrices (MRM)
The Mantel test is useful for testing associations between distance matrices, but it does not explicitly model how dissimilarities between samples depend on other variables. Just as regression extends correlation by modeling the relationship between variables, other methods extend the analysis of distance matrices by treating pairwise dissimilarities as response variables. One such technique is multiple regression on distance matrices (MRM), which models the relationship between a response distance matrix and one or more predictor distance matrices. Like Mantel tests, MRM uses permutations to test statistical significance because pairwise distances are not independent observations.
Example coming soon!