# Making comparisons for differential abundance using contrasts

Mike Morgan

#### 27/01/2022

#### Package

miloR 2.5.1

    library(miloR)
    library(SingleCellExperiment)
    library(scater)
    library(scran)
    library(dplyr)
    library(patchwork)
    library(MouseThymusAgeing)
    library(scuttle)

# 1 Introduction

We have seen how Milo uses graph neighbourhoods to model cell state abundance differences in an experiment, when comparing 2 groups. However, we are often interested in testing between 2 specific groups in our analysis when our experiment has collected data from \(\gt\) 2 groups. We can focus our analysis to a 2 group comparison and still make use of all of the data for things like dispersion estimation, by using contrasts. For an in-depth use of contrasts we recommend users refer to the `limma` and `edgeR` Biostars and Bioconductor community forum threads on the subject. Here I will give an overview of how to use contrasts in the context of a Milo analysis.

# 2 Load data

We will use the `MouseThymusAgeing` data package as there are multiple groups that we can compare.

    thy.sce <- MouseSMARTseqData() # this function downloads the full SCE object

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## field not found in version - adding

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    ## see ?MouseThymusAgeing and browseVignettes('MouseThymusAgeing') for documentation

    ## loading from cache

    thy.sce <- logNormCounts(thy.sce)
    thy.sce

    ## class: SingleCellExperiment
    ## dim: 48801 2327
    ## metadata(0):
    ## assays(2): counts logcounts
    ## rownames(48801): ERCC-00002 ERCC-00003 ... ENSMUSG00000064371
    ##   ENSMUSG00000064372
    ## rowData names(6): Geneid Chr ... Strand Length
    ## colnames(2327): B13.B002229.1_52.1.32.1_S109
    ##   B13.B002297.1_32.4.52.1_S73 ... P9.B002345.5_52.1.32.1_S93
    ##   P9.B002450.5_4.52.16.1_S261
    ## colData names(11): CellID ClusterID ... SubType sizeFactor
    ## reducedDimNames(1): PCA
    ## mainExpName: NULL
    ## altExpNames(0):

# 3 Define cell neighbourhoods

    thy.sce <- runUMAP(thy.sce) # add a UMAP for plotting results later

    thy.milo <- Milo(thy.sce) # from the SCE object
    reducedDim(thy.milo, "UMAP") <- reducedDim(thy.sce, "UMAP")

    plotUMAP(thy.milo, colour_by="SubType") + plotUMAP(thy.milo, colour_by="Age")

These UMAPs shows how the different thymic epithelial cell subtypes and cells from different aged mice are distributed across our single-cell data set. Next we build the KNN graph and define neighbourhoods to quantify cell abundance across our experimental samples.

    # we build KNN graph
    thy.milo <- buildGraph(thy.milo, k = 11, d = 40)

    ## Constructing kNN graph with k:11

    thy.milo <- makeNhoods(thy.milo, prop = 0.2, k = 11, d=40, refined = TRUE, refinement_scheme="graph") # make nhoods using graph-only as this is faster

    ## Checking valid object

    ## Running refined sampling with graph

    colData(thy.milo)$Sample <- paste(colData(thy.milo)$SortDay, colData(thy.milo)$Age, sep="_")
    thy.milo <- countCells(thy.milo, meta.data = data.frame(colData(thy.milo)), samples="Sample") # make the nhood X sample counts matrix

    ## Checking meta.data validity

    ## Counting cells in neighbourhoods

    plotNhoodSizeHist(thy.milo)

# 4 Differential abundance testing with contrasts

Now we have the pieces in place for DA testing to demonstrate how to use contrasts. We will use these contrasts to explicitly define which groups will be compared to each other.

    thy.design <- data.frame(colData(thy.milo))[,c("Sample", "SortDay", "Age")]
    thy.design <- distinct(thy.design)
    rownames(thy.design) <- thy.design$Sample
    ## Reorder rownames to match columns of nhoodCounts(milo)
    thy.design <- thy.design[colnames(nhoodCounts(thy.milo)), , drop=FALSE]
    table(thy.design$Age)

    ##
    ## 16wk  1wk 32wk  4wk 52wk
    ##    5    5    5    5    5

To demonstrate the use of contrasts we will fit the whole model to the whole data set, but we will compare sequential pairs of time points. I’ll start with week 1 vs. week 4 to illustrate the syntax.

    rownames(thy.design) <- thy.design$Sample
    contrast.1 <- c("Age1wk - Age4wk") # the syntax is <VariableName><ConditionLevel> - <VariableName><ControlLevel>

    # we need to use the ~ 0 + Variable expression here so that we have all of the levels of our variable as separate columns in our model matrix
    da_results <- testNhoods(thy.milo, design = ~ 0 + Age, design.df = thy.design, model.contrasts = contrast.1,
                             fdr.weighting="graph-overlap", norm.method="TMM")

    ## Using TMM normalisation

    ## Running with model contrasts

    ## Performing spatial FDR correction with graph-overlap weighting

    table(da_results$SpatialFDR < 0.1)

    ##
    ## FALSE  TRUE
    ##   303    41

This calculates a Fold-change and corrected P-value for each neighbourhood, which indicates whether there is significant differential abundance between conditions for 41 neighbourhoods.

You will notice that the syntax for the contrasts is quite specific. It starts with the name of the column variable that contains the different group levels; in this case it is the `Age` variable. We then define the comparison levels as `level1 - level2`. To understand this syntax we need to consider what we are concretely comparing. In this case we are asking what is the ratio of the average cell count at week1 compared to the average cell count at week 4, where the averaging is across the replicates. The reason we express this as a difference rather than a ratio is because we are dealing with the log fold change.

We can also pass multiple comparisons at the same time, for instance if we wished to compare each sequential pair of time points. This will give us a better intuition behind how to use contrasts to compare multiple groups.

    contrast.all <- c("Age1wk - Age4wk", "Age4wk - Age16wk", "Age16wk - Age32wk", "Age32wk - Age52wk")
    # contrast.all <- c("Age1wk - Age4wk", "Age16wk - Age32wk")

    # this is the edgeR code called by `testNhoods`
    model <- model.matrix(~ 0 + Age, data=thy.design)
    mod.constrast <- makeContrasts(contrasts=contrast.all, levels=model)

    mod.constrast

    ##          Contrasts
    ## Levels    Age1wk - Age4wk Age4wk - Age16wk Age16wk - Age32wk Age32wk - Age52wk
    ##   Age16wk               0               -1                 1                 0
    ##   Age1wk                1                0                 0                 0
    ##   Age32wk               0                0                -1                 1
    ##   Age4wk               -1                1                 0                 0
    ##   Age52wk               0                0                 0                -1

This shows the contrast matrix. If we want to test each of these comparisons then we need to pass them sequentially to `testNhoods`, then apply an additional multiple testing correction to the spatial FDR values.

    contrast1.res <- testNhoods(thy.milo, design=~0+ Age, design.df=thy.design, fdr.weighting="graph-overlap", model.contrasts = contrast.all)

    ## Using TMM normalisation

    ## Running with model contrasts

    ## Performing spatial FDR correction with graph-overlap weighting

    head(contrast1.res)

    ##   logFC.Age1wk...Age4wk logFC.Age4wk...Age16wk logFC.Age16wk...Age32wk
    ## 1            -1.0722182              0.6992534               1.1468262
    ## 2            -3.1757715              1.7472874               1.1817790
    ## 3             0.6278474              0.4765525              -0.5091827
    ## 4            -1.5700207              3.5017313              -3.2705208
    ## 5            -2.5839232              0.7805773              -0.4978156
    ## 6            -1.7404903              0.1478874               0.8659212
    ##   logFC.Age32wk...Age52wk   logCPM         F     PValue        FDR Nhood
    ## 1            -0.439365938 13.74027 0.7958701 0.52764761 0.62806497     1
    ## 2            -0.006899951 13.63310 2.9551250 0.01880484 0.04929387     2
    ## 3             0.089423849 13.91309 0.2851222 0.88778467 0.91467565     3
    ## 4             1.160058624 13.55110 1.8188894 0.12215676 0.19705731     4
    ## 5            -0.219126826 13.78957 1.3326204 0.25515655 0.35250544     5
    ## 6             0.444586528 13.67138 0.8545134 0.49050182 0.58791856     6
    ##   SpatialFDR
    ## 1 0.59659581
    ## 2 0.05090749
    ## 3 0.90502925
    ## 4 0.20524525
    ## 5 0.31610642
    ## 6 0.55668082

This matrix of contrasts will perform a quasi-likelihood F-test over all 5 contrasts, hence a single p-value and spatial FDR are returned. Log fold changes are returned for each contrast of the `Age` variable, which gives 1 log-fold change column for each - this is the default behaviour of `glmQLFTest` in the `edgeR` package which is what Milo uses for hypothesis testing. In general, and to avoid confusion, we recommend testing each pair of contrasts separately if these are the comparisons of interest, as shown below.

    # compare weeks 4 and 16, with week 4 as the reference.
    cont.4vs16.res <- testNhoods(thy.milo, design=~0+ Age, design.df=thy.design, fdr.weighting="graph-overlap", model.contrasts = c("Age4wk - Age16wk"))

    ## Using TMM normalisation

    ## Running with model contrasts

    ## Performing spatial FDR correction with graph-overlap weighting

    head(cont.4vs16.res)

    ##       logFC   logCPM          F     PValue       FDR Nhood SpatialFDR
    ## 1 0.6992534 13.74027 0.42693661 0.51351778 0.8575248     1  0.7655196
    ## 2 1.7472874 13.63310 2.36317200 0.12427534 0.5343840     2  0.3342613
    ## 3 0.4765525 13.91309 0.19432178 0.65935757 0.9787450     3  0.8982999
    ## 4 3.5017313 13.55110 5.83530053 0.01573361 0.2856295     4  0.1194316
    ## 5 0.7805773 13.78957 0.51021285 0.47507096 0.8253758     5  0.7305700
    ## 6 0.1478874 13.67138 0.01714257 0.89583480 1.0000000     6  1.0000000

Now we have a single logFC which compares nhood abundance between week 4 and week 16 - as we can see the LFC estimates should be the same, but the SpatialFDR will be different.

    par(mfrow=c(1, 2))
    plot(contrast1.res$logFC.Age4wk...Age16wk, cont.4vs16.res$logFC,
         xlab="4wk vs. 16wk LFC\nsingle contrast", ylab="4wk vs. 16wk LFC\nmultiple contrast")

    plot(contrast1.res$SpatialFDR, cont.4vs16.res$SpatialFDR,
         xlab="Spatial FDR\nsingle contrast", ylab="Spatial FDR\nmultiple contrast")

Contrasts are not limited to these simple pair-wise comparisons, we can also group levels together for comparisons. For instance, imagine we want to know what the effect of the cell counts in the week 1 mice is compared to all other time points.

    model <- model.matrix(~ 0 + Age, data=thy.design)
    ave.contrast <- c("Age1wk - (Age4wk + Age16wk + Age32wk + Age52wk)/4")
    mod.constrast <- makeContrasts(contrasts=ave.contrast, levels=model)

    mod.constrast

    ##          Contrasts
    ## Levels    Age1wk - (Age4wk + Age16wk + Age32wk + Age52wk)/4
    ##   Age16wk                                             -0.25
    ##   Age1wk                                               1.00
    ##   Age32wk                                             -0.25
    ##   Age4wk                                              -0.25
    ##   Age52wk                                             -0.25

In this contrasts matrix we can see that we have taken the average effect over the other time points. Now running this using `testNhoods`

    da_results <- testNhoods(thy.milo, design = ~ 0 + Age, design.df = thy.design, model.contrasts = ave.contrast, fdr.weighting="graph-overlap")

    ## Using TMM normalisation

    ## Running with model contrasts

    ## Performing spatial FDR correction with graph-overlap weighting

    table(da_results$SpatialFDR < 0.1)

    ##
    ## FALSE  TRUE
    ##   242   102

    head(da_results)

    ##         logFC   logCPM           F     PValue        FDR Nhood SpatialFDR
    ## 1 -0.08420657 13.74027 0.004451938 0.94680429 0.99970083     1  0.9997008
    ## 2 -1.27614144 13.63310 1.123669499 0.28916690 0.49738151     2  0.5767894
    ## 3  0.75302640 13.91309 0.933959702 0.33387008 0.55833869     3  0.6508382
    ## 4 -0.28896795 13.55110 0.155190643 0.69819753 0.98032633     4  0.9997008
    ## 5 -2.30217976 13.78957 4.537087368 0.03320337 0.09842994     5  0.1171179
    ## 6 -1.08546757 13.67138 1.089726650 0.29656846 0.50755995     6  0.5887190

The results table In this comparison there are 102 DA nhoods - which we can visualise on a superimposed single-cell UMAP.

    thy.milo <- buildNhoodGraph(thy.milo)

    plotUMAP(thy.milo, colour_by="SubType") + plotNhoodGraphDA(thy.milo, da_results, alpha=0.1) +
      plot_layout(guides="auto" )

    ## Adding nhood effect sizes to neighbourhood graph attributes

In these side-by-side UMAPs we can see that there is an enrichment of the Perinatal cTEC and Proliferating TEC populations in the 1 week old compared to the other time points.

For a more extensive description of the uses of contrasts please take a look at the edgeR documentation .

Session Info

    sessionInfo()

    ## R version 4.5.0 (2025-04-11 ucrt)
    ## Platform: x86_64-w64-mingw32/x64
    ## Running under: Windows Server 2022 x64 (build 20348)
    ##
    ## Matrix products: default
    ##   LAPACK version 3.12.1
    ##
    ## locale:
    ## [1] LC_COLLATE=C
    ## [2] LC_CTYPE=English_United States.utf8
    ## [3] LC_MONETARY=English_United States.utf8
    ## [4] LC_NUMERIC=C
    ## [5] LC_TIME=English_United States.utf8
    ##
    ## time zone: America/New_York
    ## tzcode source: internal
    ##
    ## attached base packages:
    ## [1] stats4    stats     graphics  grDevices utils     datasets  methods
    ## [8] base
    ##
    ## other attached packages:
    ##  [1] MouseThymusAgeing_1.17.0    patchwork_1.3.0
    ##  [3] dplyr_1.1.4                 scran_1.37.0
    ##  [5] scater_1.37.0               ggplot2_3.5.2
    ##  [7] scuttle_1.19.0              SingleCellExperiment_1.31.0
    ##  [9] SummarizedExperiment_1.39.0 Biobase_2.69.0
    ## [11] GenomicRanges_1.61.0        GenomeInfoDb_1.45.4
    ## [13] IRanges_2.43.0              S4Vectors_0.47.0
    ## [15] BiocGenerics_0.55.0         generics_0.1.4
    ## [17] MatrixGenerics_1.21.0       matrixStats_1.5.0
    ## [19] miloR_2.5.1                 edgeR_4.7.2
    ## [21] limma_3.65.1                BiocStyle_2.37.0
    ##
    ## loaded via a namespace (and not attached):
    ##   [1] RColorBrewer_1.1-3   jsonlite_2.0.0       magrittr_2.0.3
    ##   [4] ggbeeswarm_0.7.2     magick_2.8.6         farver_2.1.2
    ##   [7] rmarkdown_2.29       vctrs_0.6.5          memoise_2.0.1
    ##  [10] tinytex_0.57         htmltools_0.5.8.1    S4Arrays_1.9.1
    ##  [13] AnnotationHub_3.99.5 curl_6.2.3           BiocNeighbors_2.3.1
    ##  [16] SparseArray_1.9.0    sass_0.4.10          pracma_2.4.4
    ##  [19] bslib_0.9.0          httr2_1.1.2          cachem_1.1.0
    ##  [22] igraph_2.1.4         lifecycle_1.0.4      pkgconfig_2.0.3
    ##  [25] rsvd_1.0.5           Matrix_1.7-3         R6_2.6.1
    ##  [28] fastmap_1.2.0        digest_0.6.37        numDeriv_2016.8-1.1
    ##  [31] AnnotationDbi_1.71.0 dqrng_0.4.1          irlba_2.3.5.1
    ##  [34] ExperimentHub_2.99.5 RSQLite_2.4.0        beachmat_2.25.1
    ##  [37] filelock_1.0.3       labeling_0.4.3       httr_1.4.7
    ##  [40] polyclip_1.10-7      abind_1.4-8          compiler_4.5.0
    ##  [43] bit64_4.6.0-1        withr_3.0.2          BiocParallel_1.43.3
    ##  [46] viridis_0.6.5        DBI_1.2.3            ggforce_0.4.2
    ##  [49] MASS_7.3-65          rappdirs_0.3.3       DelayedArray_0.35.1
    ##  [52] bluster_1.19.0       gtools_3.9.5         tools_4.5.0
    ##  [55] vipor_0.4.7          beeswarm_0.4.0       glue_1.8.0
    ##  [58] grid_4.5.0           cluster_2.1.8.1      gtable_0.3.6
    ##  [61] tidyr_1.3.1          BiocSingular_1.25.0  tidygraph_1.3.1
    ##  [64] ScaledMatrix_1.17.0  metapod_1.17.0       XVector_0.49.0
    ##  [67] ggrepel_0.9.6        BiocVersion_3.22.0   pillar_1.10.2
    ##  [70] stringr_1.5.1        splines_4.5.0        tweenr_2.0.3
    ##  [73] BiocFileCache_2.99.5 lattice_0.22-7       FNN_1.1.4.1
    ##  [76] bit_4.6.0            tidyselect_1.2.1     locfit_1.5-9.12
    ##  [79] Biostrings_2.77.1    knitr_1.50           gridExtra_2.3
    ##  [82] bookdown_0.43        xfun_0.52            graphlayouts_1.2.2
    ##  [85] statmod_1.5.0        stringi_1.8.7        UCSC.utils_1.5.0
    ##  [88] yaml_2.3.10          evaluate_1.0.3       codetools_0.2-20
    ##  [91] ggraph_2.2.1         tibble_3.2.1         BiocManager_1.30.25
    ##  [94] cli_3.6.5            uwot_0.2.3           jquerylib_0.1.4
    ##  [97] dichromat_2.0-0.1    Rcpp_1.0.14          dbplyr_2.5.0
    ## [100] png_0.1-8            parallel_4.5.0       blob_1.2.4
    ## [103] viridisLite_0.4.2    scales_1.4.0         purrr_1.0.4
    ## [106] crayon_1.5.3         rlang_1.1.6          cowplot_1.1.3
    ## [109] KEGGREST_1.49.0