17  Correlation

In correlation — or association analysis more generally — we can evaluate the relationships between numeric variables. These variables can be taxonomic features or patient metadata. For instance, we might be interested in which taxonomic features are present simultaneously with others, or whether body weight is associated with the abundance of certain features. In this chapter, we will demonstrate how to perform correlation analysis with mia’s getCrossAssociation() method.

17.1 Features vs. features

Here we demonstrate how to analyze which bacteria co-exist in the dataset (Potbhare et al. 2022).

Skin microbiota diversity among genetically unrelated individuals of Indian origin. Potbhare et al. (2022). PeerJ 10:e13075. doi:10.7717/peerj.13075.
library(mia)

data("peerj13075", package = "mia")
tse <- peerj13075

# Agglomerate to certain taxonomy level
tse <- agglomerateByRank(tse, rank = "class")
tse <- addPrevalence(tse)
tse <- subsetBy(tse, rows = prevalence > 0.5, collapse = TRUE)

# Apply clr-transform
tse <- transformAssay(tse, method = "clr", pseudocount = 0.5)

# Get correlation results
res <- getCrossAssociation(
    tse, tse,
    assay.type1 = "clr", assay.type2 = "clr",
    test.signif = TRUE, mode = "matrix"
)

By default, getCrossAssociation() calculates Kendall’s rank correlation (Kendall 1938), here between the clr-transformed abundances (Fernandes et al. 2014); other methods can be chosen with the method argument. The p-values are adjusted for multiple testing with the Benjamini-Hochberg method (Benjamini and Hochberg 1995).

A new measure of rank correlation. Kendall (1938). Biometrika 30:81–93. doi:10.1093/biomet/30.1-2.81.
Unifying the analysis of high-throughput sequencing datasets: Characterizing RNA-seq, 16S rRNA gene sequencing and selective growth experiments by compositional data analysis. Fernandes et al. (2014). Microbiome 2:15. doi:10.1186/2049-2618-2-15.
Controlling the false discovery rate: A practical and powerful approach to multiple testing. Benjamini et al. (1995). J R Stat Soc Series B 57:289–300. doi:10.1111/J.2517-6161.1995.TB02031.X.
qgraph: Network visualizations of relationships in psychometric data. Epskamp et al. (2012). J Stat Softw 48:1–18. doi:10.18637/jss.v048.i04.

We can visualize the result with a heatmap as we do later in this chapter, or we can visualize the results with a correlation network plot (Epskamp et al. 2012) as done below (Figure 17.1).

library(qgraph)

# Create correlation network plot
qgraph(
    res$cor,
    layout = "spring", labels = colnames(res$cor),
    label.cex = 1.2, theme = "colorblind",
    node.width = 1.5, node.height = 2, label.scale.equal = TRUE
)
Spring-layout network graph with one labeled node per class, connected by edges whose color shows positive or negative correlation and whose width shows its strength.
Figure 17.1: Correlation network of the classes in the peerj13075 data, based on correlations between CLR-transformed abundances. Nodes are classes, and edge color (blue: positive, red: negative) and width show the sign and strength of the correlation.

You can find more on networks in the extra materials.

17.2 Features vs. metadata

Now, we can calculate alpha diversity indices, and evaluate if they have significant association with taxonomic features.

# Calculate diversity measures
index <- c(
    "shannon", "log_modulo_skewness", "coverage", "inverse_simpson", "gini"
)
tse <- addAlpha(tse, index = index)

# Get correlation results
res <- getCrossAssociation(
    tse, tse,
    assay.type1 = "clr", col.var2 = index,
    test.signif = TRUE, mode = "matrix"
)

Below, we present the results using a heatmap visualization with the help of the ComplexHeatmap (Gu et al. 2016) and shadowtext R packages (Figure 17.2).

Complex heatmaps reveal patterns and correlations in multidimensional genomic data. Gu et al. (2016). Bioinformatics 32:2847–2849. doi:10.1093/bioinformatics/btw313.
library(ComplexHeatmap)
library(shadowtext)

# Function for marking significant correlations with "X"
add_signif <- function(j, i, x, y, width, height, fill) {
    # If the p-value is under threshold
    if (!is.na(res$p_adj[i, j]) & res$p_adj[i, j] < 0.05) {
        # Print "X"
        grid.shadowtext(
            sprintf("%s", "X"), x, y,
            gp = gpar(fontsize = 8, col = "#f5f5f5")
        )
    }
}

# Create a heatmap
p <- Heatmap(res$cor,
    # Mark significant correlations with X
    cell_fun = add_signif,
    heatmap_legend_param = list(
        title = "correlation", legend_height = unit(5, "cm")
    ),
    column_names_rot = 45
)
p
Clustered heatmap with classes as rows and five alpha diversity indices as columns, filled by correlation on a color scale, with an X in the cells of significant correlations.
Figure 17.2: Heatmap of correlations between CLR-transformed abundances of classes (rows) and alpha diversity indices (columns) in the peerj13075 data. Significant correlations (adjusted p-value < 0.05) are marked with X.

17.3 Metadata vs. metadata

Finally, we demonstrate how to calculate correlation between sample metadata variables. Here we estimate correlation between alpha diversity measures.

Compared to the solution in Section 12.2.2.1, getCrossAssociation() allows us to calculate correlations in bulk easily, without the need for looping. The correlations are shown in Figure 17.3.

# Get correlation results
res <- getCrossAssociation(
    tse, tse,
    col.var1 = index, col.var2 = index,
    test.signif = TRUE, mode = "matrix"
)

# Create a heatmap and store it
p <- Heatmap(res$cor,
    # Mark significant correlations with X
    cell_fun = add_signif,
    heatmap_legend_param = list(
        title = "correlation", legend_height = unit(5, "cm")
    ),
    column_names_rot = 45
)
p
Clustered square heatmap with the five alpha diversity indices on both axes, filled by correlation on a color scale, with an X in the cells of significant correlations.
Figure 17.3: Heatmap of correlations between alpha diversity indices in the peerj13075 data. Significant correlations (adjusted p-value < 0.05) are marked with X.
Cross-association

See Chapter 20 for further information on correlation and association analyses.

17.4 Exercises

We use the Tengeler2020 dataset.

Solve the exercises in order, as each exercise continues from the previous one. Try to solve each exercise yourself before opening the solution.

Exercise 1: Correlation between taxonomic features

Goal: Calculate correlations between taxonomic features and find the results.

  1. Load the Tengeler2020 dataset from the mia package and store it in a variable called tse.

  2. Agglomerate the data to the Family rank. Then add the prevalence, and combine the families with a prevalence of 0.5 or less into “Other”. How many features are left?

  3. Apply the clr transformation to the counts assay with a pseudocount of 1.

  4. Calculate the correlations between all pairs of families from the clr assay with getCrossAssociation(). Give tse as both the first and the second object, test the significance of the correlations (test.signif = TRUE) and return the results as matrices (mode = "matrix"). Store the result in res.

  5. Check the names of the elements in res. Show the correlations rounded to two decimals.

  6. Count how many pairs of families have an adjusted p-value below 0.05. The matrix is symmetric and its diagonal compares each family with itself, so count only the values above the diagonal.

  7. What do the values on the diagonal of the correlation matrix show? What does a correlation close to 1, close to -1 and close to 0 mean? Why do we use adjusted p-values instead of raw p-values?

Useful functions: data(), mia::agglomerateByRank(), mia::addPrevalence(), mia::subsetBy(), nrow(), mia::transformAssay(), mia::getCrossAssociation(), names(), round(), upper.tri(), sum()

library(mia)

# 1. Load the data
data("Tengeler2020", package = "mia")
tse <- Tengeler2020

# 2. Agglomerate to prevalent families
tse <- agglomerateByRank(tse, rank = "Family")
tse <- addPrevalence(tse)
tse <- subsetBy(tse, rows = prevalence > 0.5, collapse = TRUE)
nrow(tse)
##  [1] 10

# 3. clr transformation
tse <- transformAssay(
    tse,
    assay.type = "counts", method = "clr", pseudocount = 1
)

# 4. Correlations between families
res <- getCrossAssociation(
    tse, tse,
    assay.type1 = "clr", assay.type2 = "clr",
    test.signif = TRUE, mode = "matrix"
)

# 5. Elements of the result and the correlations
names(res)
##  [1] "cor"   "pval"  "p_adj"
round(res$cor, 2)
##                      Bacteroidaceae Enterobacteriaceae Erysipelotrichaceae
##  Bacteroidaceae                1.00              -0.20               -0.06
##  Enterobacteriaceae           -0.20               1.00               -0.11
##  Erysipelotrichaceae          -0.06              -0.11                1.00
##  Eubacteriaceae               -0.32               0.28               -0.10
##  Lachnospiraceae               0.13              -0.32                0.48
##  Porphyromonadaceae           -0.26              -0.07                0.04
##  Rikenellaceae                 0.29              -0.29                0.33
##  Ruminococcaceae              -0.40              -0.01                0.06
##  Verrucomicrobiaceae           0.15              -0.21                0.51
##  Other                         0.14               0.03               -0.44
##                      Eubacteriaceae Lachnospiraceae Porphyromonadaceae
##  Bacteroidaceae               -0.32            0.13              -0.26
##  Enterobacteriaceae            0.28           -0.32              -0.07
##  Erysipelotrichaceae          -0.10            0.48               0.04
##  Eubacteriaceae                1.00           -0.43               0.32
##  Lachnospiraceae              -0.43            1.00              -0.08
##  Porphyromonadaceae            0.32           -0.08               1.00
##  Rikenellaceae                -0.38            0.53               0.07
##  Ruminococcaceae               0.03            0.12               0.18
##  Verrucomicrobiaceae          -0.30            0.74               0.03
##  Other                        -0.12           -0.18              -0.39
##                      Rikenellaceae Ruminococcaceae Verrucomicrobiaceae Other
##  Bacteroidaceae               0.29           -0.40                0.15  0.14
##  Enterobacteriaceae          -0.29           -0.01               -0.21  0.03
##  Erysipelotrichaceae          0.33            0.06                0.51 -0.44
##  Eubacteriaceae              -0.38            0.03               -0.30 -0.12
##  Lachnospiraceae              0.53            0.12                0.74 -0.18
##  Porphyromonadaceae           0.07            0.18                0.03 -0.39
##  Rikenellaceae                1.00            0.02                0.53 -0.20
##  Ruminococcaceae              0.02            1.00                0.07 -0.25
##  Verrucomicrobiaceae          0.53            0.07                1.00 -0.28
##  Other                       -0.20           -0.25               -0.28  1.00

# 6. Number of family pairs with adjusted p-value below 0.05
sum(res$p_adj[upper.tri(res$p_adj)] < 0.05, na.rm = TRUE)
##  [1] 11
  1. upper.tri() selects the values above the diagonal, so each pair of families is counted once and the comparisons of a family with itself are left out.

  2. The diagonal shows the correlation of each family with itself, which is always 1. These values should be ignored, and so should the duplicates, as the matrix is symmetric. A correlation close to 1 means that the two families tend to be abundant in the same samples. A correlation close to -1 means that when one family is abundant, the other tends to be rare. A correlation close to 0 means that there is no clear association. When many correlations are tested at once, some of them are significant just by chance. The adjusted p-values (p_adj) correct for this multiple testing.

Exercise 2: Correlation network

Goal: Visualize the correlations between taxonomic features as a network.

  1. Visualize the correlation matrix res$cor from Exercise 1 as a network with qgraph(). Use the spring layout (layout = "spring"), label the nodes with the column names of the matrix and use theme = "colorblind".

  2. How do you read the network? What do the nodes, the color of the edges and the width of the edges show?

Useful functions: qgraph::qgraph(), colnames()

library(qgraph)

# 1. Correlation network
qgraph(
    res$cor,
    layout = "spring", labels = colnames(res$cor),
    theme = "colorblind", label.scale.equal = TRUE,
    label.cex = 1.1, vsize = 12
)

  1. Each node is a family, and each edge shows the correlation between two families. The color of an edge shows the sign of the correlation (positive or negative), and the width shows its strength. In the spring layout, strongly connected families are placed close to each other. A group of families connected with strong positive edges tends to occur together in the samples.
Exercise 3: Correlation between taxonomic features and alpha diversity

Goal: Calculate correlations between taxonomic features and sample metadata.

  1. Calculate the alpha diversity indices "shannon", "observed", "gini" and "inverse_simpson" from the counts assay with addAlpha(). Store the names of the indices in a vector called index.

  2. Calculate the correlations between the families in the clr assay and the alpha diversity indices with getCrossAssociation(). Give the indices with the col.var2 argument, test the significance and return the results as matrices. To hide the warnings about ties, set show.warnings = FALSE.

  3. Visualize the correlations with a heatmap.

  4. Show the adjusted p-values rounded to three decimals. Which pairs of a family and an index have an adjusted p-value below 0.05?

  5. How do you read the heatmap? What would a positive correlation between a family and Shannon diversity mean?

Useful functions: mia::addAlpha(), mia::getCrossAssociation(), ComplexHeatmap::Heatmap(), round()

library(ComplexHeatmap)

# 1. Alpha diversity indices
index <- c("shannon", "observed", "gini", "inverse_simpson")
tse <- addAlpha(tse, assay.type = "counts", index = index)

# 2. Correlations between families and alpha diversity indices
res <- getCrossAssociation(
    tse, tse,
    assay.type1 = "clr", col.var2 = index,
    test.signif = TRUE, mode = "matrix", show.warnings = FALSE
)

# 3. Heatmap of the correlations
Heatmap(res$cor, name = "correlation")


# 4. Adjusted p-values
round(res$p_adj, 3)
##                      shannon observed  gini inverse_simpson
##  Bacteroidaceae        0.000    0.168 0.000           0.000
##  Enterobacteriaceae    0.823    0.628 0.689           0.958
##  Erysipelotrichaceae   0.640    0.010 0.726           0.416
##  Eubacteriaceae        0.628    0.501 0.501           0.800
##  Lachnospiraceae       0.967    0.000 0.812           0.726
##  Porphyromonadaceae    0.316    0.726 0.379           0.406
##  Rikenellaceae         0.194    0.000 0.168           0.406
##  Ruminococcaceae       0.017    0.800 0.040           0.011
##  Verrucomicrobiaceae   0.915    0.000 0.739           0.835
##  Other                 0.261    0.100 0.406           0.194
  1. Each row is a family and each column an alpha diversity index, and the color of a cell shows the correlation. The rows and columns are ordered with hierarchical clustering, so that families with similar correlation patterns are next to each other. A positive correlation with Shannon diversity means that samples with a higher abundance of the family tend to have higher diversity. A correlation does not tell whether the family causes the difference in diversity. Note that Gini is an inequality index: high values mean low evenness, so its correlations tend to have the opposite sign compared to the diversity indices.
Exercise 4: Correlation between sample metadata variables

Goal: Calculate correlations between sample metadata variables.

  1. Calculate the correlations between the alpha diversity indices in index with getCrossAssociation(). Give the indices with both col.var1 and col.var2, test the significance, return the results as matrices and set show.warnings = FALSE.

  2. Visualize the correlations with a heatmap.

  3. Make a scatter plot with the Shannon diversity on the x-axis and the inverse Simpson diversity on the y-axis. Add a linear regression line to the plot.

  4. How do you read the scatter plot? How does it relate to the correlation between the two indices in the heatmap?

Useful functions: mia::getCrossAssociation(), ComplexHeatmap::Heatmap(), scater::plotColData(), ggplot2::geom_smooth()

library(scater)

# 1. Correlations between alpha diversity indices
res <- getCrossAssociation(
    tse, tse,
    col.var1 = index, col.var2 = index,
    test.signif = TRUE, mode = "matrix", show.warnings = FALSE
)

# 2. Heatmap of the correlations
Heatmap(res$cor, name = "correlation")


# 3. Scatter plot with a linear regression line
plotColData(tse, x = "shannon", y = "inverse_simpson", point_alpha = 1) +
    geom_smooth(method = "lm") +
    labs(x = "Shannon diversity", y = "Inverse Simpson diversity")

  1. In the scatter plot, each point is a sample. The scatter plot shows the same relationship that is summarized by a single correlation value in the heatmap. By default, getCrossAssociation() calculates Kendall’s rank correlation, which measures whether one index tends to increase (or decrease) when the other increases, even if the relationship is not linear. If the points form a clear increasing or decreasing trend, the two indices are strongly correlated and carry largely the same information. If the points are widely scattered, the correlation is weak and the indices describe different aspects of the communities. The scatter plot also shows whether the relationship is driven by a few outlying samples, which a single correlation value cannot show.
Back to top