# Differential abundance testing with Milo - Mouse gastrulation example

Emma Dann and Mike Morgan

#### 4 June 2025

#### Package

miloR 2.5.1

    library(miloR)
    library(SingleCellExperiment)
    library(scater)
    library(scran)
    library(dplyr)
    library(patchwork)
    library(MouseGastrulationData)

# 1 Load data

For this vignette we will use the mouse gastrulation single-cell data from Pijuan-Sala et al. 2019. The dataset can be downloaded as a `SingleCellExperiment` object from the `MouseGastrulationData` package on Bioconductor. To make computations faster, here we will download just a subset of samples, 4 samples at stage E7 and 4 samples at stage E7.5.

This dataset has already been pre-processed and contains a `pca.corrected` dimensionality reduction, which was built after batch correction using `fastMNN`.

    select_samples <- c(2,  3,  6, 4, #15,
                        # 19,
                        10, 14#, 20 #30
                        #31, 32
                        )
    embryo_data = EmbryoAtlasData(samples = select_samples)
    embryo_data

    ## class: SingleCellExperiment
    ## dim: 29452 7558
    ## metadata(0):
    ## assays(1): counts
    ## rownames(29452): ENSMUSG00000051951 ENSMUSG00000089699 ...
    ##   ENSMUSG00000096730 ENSMUSG00000095742
    ## rowData names(2): ENSEMBL SYMBOL
    ## colnames(7558): cell_361 cell_362 ... cell_29013 cell_29014
    ## colData names(17): cell barcode ... colour sizeFactor
    ## reducedDimNames(2): pca.corrected umap
    ## mainExpName: NULL
    ## altExpNames(0):

# 2 Visualize the data

We recompute the UMAP embedding for this subset of cells to visualize the data.

    embryo_data <- embryo_data[,apply(reducedDim(embryo_data, "pca.corrected"), 1, function(x) !all(is.na(x)))]
    embryo_data <- runUMAP(embryo_data, dimred = "pca.corrected", name = 'umap')

    plotReducedDim(embryo_data, colour_by="stage", dimred = "umap")

We will test for significant differences in abundance of cells between these stages of development, and the associated gene signatures.

# 3 Differential abundance testing

## 3.1 Create a Milo object

For differential abundance analysis on graph neighbourhoods we first construct a `Milo` object. This extends the `SingleCellExperiment` class to store information about neighbourhoods on the KNN graph.

    embryo_milo <- Milo(embryo_data)
    embryo_milo

    ## class: Milo
    ## dim: 29452 6875
    ## metadata(0):
    ## assays(1): counts
    ## rownames(29452): ENSMUSG00000051951 ENSMUSG00000089699 ...
    ##   ENSMUSG00000096730 ENSMUSG00000095742
    ## rowData names(2): ENSEMBL SYMBOL
    ## colnames(6875): cell_361 cell_362 ... cell_29013 cell_29014
    ## colData names(17): cell barcode ... colour sizeFactor
    ## reducedDimNames(2): pca.corrected umap
    ## mainExpName: NULL
    ## altExpNames(0):
    ## nhoods dimensions(2): 1 1
    ## nhoodCounts dimensions(2): 1 1
    ## nhoodDistances dimension(1): 0
    ## graph names(0):
    ## nhoodIndex names(1): 0
    ## nhoodExpression dimension(2): 1 1
    ## nhoodReducedDim names(0):
    ## nhoodGraph names(0):
    ## nhoodAdjacency dimension(2): 1 1

## 3.2 Construct KNN graph

We need to add the KNN graph to the Milo object. This is stored in the `graph` slot, in `igraph` format. The `miloR` package includes functionality to build and store the graph from the PCA dimensions stored in the `reducedDim` slot. In this case, we specify that we want to build the graph from the MNN corrected PCA dimensions.

For graph building you need to define a few parameters:

- `d`: the number of reduced dimensions to use for KNN refinement. We recommend using the same \(d\) used for KNN graph building, or to select PCs by inspecting the scree plot.
- `k`: this affects the power of DA testing, since we need to have enough cells from each sample represented in a neighbourhood to estimate the variance between replicates. On the other side, increasing \(k\) too much might lead to over-smoothing. We suggest to start by using the same value for \(k\) used for KNN graph building for clustering and UMAP visualization. We will later use some heuristics to evaluate whether the value of \(k\) should be increased.

    embryo_milo <- buildGraph(embryo_milo, k = 30, d = 30, reduced.dim = "pca.corrected")

Alternatively, one can add a precomputed KNN graph (for example constructed with Seurat or scanpy) to the `graph` slot using the adjacency matrix, through the helper function `buildFromAdjacency`.

## 3.3 Defining representative neighbourhoods on the KNN graph

We define the neighbourhood of a cell, the index, as the group of cells connected by an edge in the KNN graph to the index cell. For efficiency, we don’t test for DA in the neighbourhood of every cell, but we sample as indices a subset of representative cells, using a KNN sampling algorithm used by Gut et al. 2015.

As well as \(d\) and \(k\), for sampling we need to define a few additional parameters:

- `prop`: the proportion of cells to randomly sample to start with. We suggest using `prop=0.1` for datasets of less than 30k cells. For bigger datasets using `prop=0.05` should be sufficient (and makes computation faster).
- `refined`: indicates whether you want to use the sampling refinement algorithm, or just pick cells at random. The default and recommended way to go is to use refinement. The only situation in which you might consider using `random` instead, is if you have batch corrected your data with a graph based correction algorithm, such as BBKNN, but the results of DA testing will be suboptimal.

    embryo_milo <- makeNhoods(embryo_milo, prop = 0.1, k = 30, d=30, refined = TRUE, reduced_dims = "pca.corrected")

Once we have defined neighbourhoods, we plot the distribution of neighbourhood sizes (i.e. how many cells form each neighbourhood) to evaluate whether the value of \(k\) used for graph building was appropriate. We can check this out using the `plotNhoodSizeHist` function.

As a rule of thumb we want to have an average neighbourhood size over 5 x N_samples. If the mean is lower, or if the distribution is

    plotNhoodSizeHist(embryo_milo)

## 3.4 Counting cells in neighbourhoods

Milo leverages the variation in cell numbers between replicates for the same experimental condition to test for differential abundance. Therefore we have to count how many cells from each sample are in each neighbourhood. We need to use the cell metadata and specify which column contains the sample information.

    embryo_milo <- countCells(embryo_milo, meta.data = as.data.frame(colData(embryo_milo)), sample="sample")

This adds to the `Milo` object a \(n \times m\) matrix, where \(n\) is the number of neighbourhoods and \(m\) is the number of experimental samples. Values indicate the number of cells from each sample counted in a neighbourhood. This count matrix will be used for DA testing.

    head(nhoodCounts(embryo_milo))

    ## 6 x 6 sparse Matrix of class "dgCMatrix"
    ##   2  3  6 4 10 14
    ## 1 1 11 28 6  9  2
    ## 2 5  3 69 4 12  9
    ## 3 1  1 21 1 48 15
    ## 4 7  4 48 5  8  4
    ## 5 .  .  4 1 50 18
    ## 6 .  .  3 . 41  8

## 3.5 Defining experimental design

Now we are all set to test for differential abundance in neighbourhoods. We implement this hypothesis testing in a generalized linear model (GLM) framework, specifically using the Negative Binomial GLM implementation in `edgeR`.

We first need to think about our experimental design. The design matrix should match each sample to the experimental condition of interest for DA testing. In this case, we want to detect DA between embryonic stages, stored in the `stage` column of the dataset `colData`. We also include the `sequencing.batch` column in the design matrix. This represents a known technical covariate that we want to account for in DA testing.

    embryo_design <- data.frame(colData(embryo_milo))[,c("sample", "stage", "sequencing.batch")]

    ## Convert batch info from integer to factor
    embryo_design$sequencing.batch <- as.factor(embryo_design$sequencing.batch)
    embryo_design <- distinct(embryo_design)
    rownames(embryo_design) <- embryo_design$sample

    embryo_design

    ##    sample stage sequencing.batch
    ## 2       2  E7.5                1
    ## 3       3  E7.5                1
    ## 6       6  E7.5                1
    ## 4       4  E7.5                1
    ## 10     10  E7.0                1
    ## 14     14  E7.0                2

## 3.6 Computing neighbourhood connectivity

Milo uses an adaptation of the Spatial FDR correction introduced by cydar, where we correct p-values accounting for the amount of overlap between neighbourhoods. Specifically, each hypothesis test P-value is weighted by the reciprocal of the kth nearest neighbour distance. To use this statistic we first need to store the distances between nearest neighbors in the Milo object. This is done by the `calcNhoodDistance` function (N.B. this step is the most time consuming of the analysis workflow and might take a couple of minutes for large datasets).

    embryo_milo <- calcNhoodDistance(embryo_milo, d=30, reduced.dim = "pca.corrected")

## 3.7 Testing

Now we can do the DA test, explicitly defining our experimental design. In this case, we want to test for differences between experimental stages, while accounting for the variability between technical batches (You can find more info on how to use formulas to define a testing design in R here)

    da_results <- testNhoods(embryo_milo, design = ~ sequencing.batch + stage, design.df = embryo_design, reduced.dim="pca.corrected")
    head(da_results)

    ##        logFC   logCPM         F       PValue          FDR Nhood   SpatialFDR
    ## 1  1.2248265 11.23671  1.315051 2.516854e-01 3.044581e-01     1 3.071792e-01
    ## 2  0.9786265 11.61182  1.167601 2.800878e-01 3.352114e-01     2 3.380802e-01
    ## 3 -2.6757417 11.59623 11.423364 7.459591e-04 1.854595e-03     3 1.797906e-03
    ## 4  1.5450770 11.40726  2.410157 1.207847e-01 1.566372e-01     4 1.584771e-01
    ## 5 -4.6765181 11.52996 26.184103 3.551589e-07 3.898086e-06     5 3.176566e-06
    ## 6 -5.1519344 10.99888 20.281286 7.261792e-06 4.299746e-05     6 3.692355e-05

This calculates a Fold-change and corrected P-value for each neighbourhood, which indicates whether there is significant differential abundance between developmental stages. The main statistics we consider here are:

- `logFC`: indicates the log-Fold change in cell numbers between samples from E7.5 and samples from E7.0
- `PValue`: reports P-values before FDR correction
- `SpatialFDR`: reports P-values corrected for multiple testing accounting for overlap between neighbourhoods

    da_results %>%
      arrange(SpatialFDR) %>%
      head()

    ##         logFC   logCPM        F       PValue          FDR Nhood   SpatialFDR
    ## 112 -7.500177 12.12443 43.48393 6.117728e-11 1.376489e-08   112 1.041868e-08
    ## 163 -6.816000 11.74749 44.78773 3.209859e-11 1.376489e-08   163 1.041868e-08
    ## 195 -5.793625 11.83895 40.37584 2.858265e-10 3.953605e-08   195 2.902138e-08
    ## 436 -6.274584 11.83508 39.96016 3.514315e-10 3.953605e-08   436 2.902138e-08
    ## 432 -5.577575 11.58541 39.33656 4.792403e-10 4.313163e-08   432 3.178901e-08
    ## 29  -5.588152 11.74070 38.45227 7.443397e-10 5.582548e-08    29 4.098030e-08

# 4 Inspecting DA testing results

We can start inspecting the results of our DA analysis from a couple of standard diagnostic plots. We first inspect the distribution of uncorrected P values, to verify that the test was balanced.

    ggplot(da_results, aes(PValue)) + geom_histogram(bins=50)

Then we visualize the test results with a volcano plot (remember that each point here represents a neighbourhood, not a cell).

    ggplot(da_results, aes(logFC, -log10(SpatialFDR))) +
      geom_point() +
      geom_hline(yintercept = 1) ## Mark significance threshold (10% FDR)

Looks like we have detected several neighbourhoods were there is a significant difference in cell abundances between developmental stages.

To visualize DA results relating them to the embedding of single cells, we can build an abstracted graph of neighbourhoods that we can superimpose on the single-cell embedding. Here each node represents a neighbourhood, while edges indicate how many cells two neighbourhoods have in common. Here the layout of nodes is determined by the position of the index cell in the UMAP embedding of all single-cells. The neighbourhoods displaying significant DA are colored by their log-Fold Change.

    embryo_milo <- buildNhoodGraph(embryo_milo)

    ## Plot single-cell UMAP
    umap_pl <- plotReducedDim(embryo_milo, dimred = "umap", colour_by="stage", text_by = "celltype",
                              text_size = 3, point_size=0.5) +
      guides(fill="none")

    ## Plot neighbourhood graph
    nh_graph_pl <- plotNhoodGraphDA(embryo_milo, da_results, layout="umap",alpha=0.1)

    umap_pl + nh_graph_pl +
      plot_layout(guides="collect")

We might also be interested in visualizing whether DA is particularly evident in certain cell types. To do this, we assign a cell type label to each neighbourhood by finding the most abundant cell type within cells in each neighbourhood. We can label neighbourhoods in the results `data.frame` using the function `annotateNhoods`. This also saves the fraction of cells harbouring the label.

    da_results <- annotateNhoods(embryo_milo, da_results, coldata_col = "celltype")
    head(da_results)

    ##        logFC   logCPM         F       PValue          FDR Nhood   SpatialFDR
    ## 1  1.2248265 11.23671  1.315051 2.516854e-01 3.044581e-01     1 3.071792e-01
    ## 2  0.9786265 11.61182  1.167601 2.800878e-01 3.352114e-01     2 3.380802e-01
    ## 3 -2.6757417 11.59623 11.423364 7.459591e-04 1.854595e-03     3 1.797906e-03
    ## 4  1.5450770 11.40726  2.410157 1.207847e-01 1.566372e-01     4 1.584771e-01
    ## 5 -4.6765181 11.52996 26.184103 3.551589e-07 3.898086e-06     5 3.176566e-06
    ## 6 -5.1519344 10.99888 20.281286 7.261792e-06 4.299746e-05     6 3.692355e-05
    ##               celltype celltype_fraction
    ## 1    Visceral endoderm         0.9824561
    ## 2         ExE ectoderm         1.0000000
    ## 3         ExE endoderm         1.0000000
    ## 4 Rostral neurectoderm         0.6315789
    ## 5     Primitive Streak         0.8082192
    ## 6     Primitive Streak         0.9807692

While neighbourhoods tend to be homogeneous, we can define a threshold for `celltype_fraction` to exclude neighbourhoods that are a mix of cell types.

    ggplot(da_results, aes(celltype_fraction)) + geom_histogram(bins=50)

    da_results$celltype <- ifelse(da_results$celltype_fraction < 0.7, "Mixed", da_results$celltype)

Now we can visualize the distribution of DA Fold Changes in different cell types

    plotDAbeeswarm(da_results, group.by = "celltype")

This is already quite informative: we can see that certain early development cell types, such as epiblast and primitive streak, are enriched in the earliest time stage, while others are enriched later in development, such as ectoderm cells. Interestingly, we also see plenty of DA neighbourhood with a mixed label. This could indicate that transitional states show changes in abundance in time.

# 5 Finding markers of DA populations

Once you have found your neighbourhoods showindg significant DA between conditions, you might want to find gene signatures specific to the cells in those neighbourhoods. The function `findNhoodGroupMarkers` runs a one-VS-all differential gene expression test to identify marker genes for a group of neighbourhoods of interest. Before running this function you will need to define your neighbourhood groups depending on your biological question, that need to be stored as a `NhoodGroup` column in the `da_results` data.frame.

### 5.0.1 Custom grouping

In a case where all the DA neighbourhoods seem to belong to the same region of the graph, you might just want to test the significant DA neighbourhoods with the same logFC against all the rest (N.B. for illustration purposes, here I am testing on a randomly selected set of 10 genes).

    ## Add log normalized count to Milo object
    embryo_milo <- logNormCounts(embryo_milo)

    da_results$NhoodGroup <- as.numeric(da_results$SpatialFDR < 0.1 & da_results$logFC < 0)
    da_nhood_markers <- findNhoodGroupMarkers(embryo_milo, da_results, subset.row = rownames(embryo_milo)[1:10])

    ## Warning: Zero sample variances detected, have been offset away from zero
    ## Warning: Zero sample variances detected, have been offset away from zero

    head(da_nhood_markers)

    ##               GeneID       logFC_0 adj.P.Val_0       logFC_1 adj.P.Val_1
    ## 1 ENSMUSG00000025900  2.334586e-05  1.00000000 -2.334586e-05  1.00000000
    ## 2 ENSMUSG00000025902  7.545143e-02  0.01150014 -7.545143e-02  0.01150014
    ## 3 ENSMUSG00000025903 -6.164851e-02  0.01150014  6.164851e-02  0.01150014
    ## 4 ENSMUSG00000033813 -4.063097e-02  0.17038887  4.063097e-02  0.17038887
    ## 5 ENSMUSG00000033845 -4.046559e-02  0.18748737  4.046559e-02  0.18748737
    ## 6 ENSMUSG00000051951  0.000000e+00  1.00000000  0.000000e+00  1.00000000

For this analysis we recommend aggregating the neighbourhood expression profiles by experimental samples (the same used for DA testing), by setting `aggregate.samples=TRUE`. This way single-cells will not be considered as “replicates” during DGE testing, and dispersion will be estimated between true biological replicates. Like so:

    da_nhood_markers <- findNhoodGroupMarkers(embryo_milo, da_results, subset.row = rownames(embryo_milo)[1:10],
                                              aggregate.samples = TRUE, sample_col = "sample")

    ## Warning: Zero sample variances detected, have been offset away from zero
    ## Warning: Zero sample variances detected, have been offset away from zero

    head(da_nhood_markers)

    ##               GeneID      logFC_0 adj.P.Val_0      logFC_1 adj.P.Val_1
    ## 1 ENSMUSG00000025900  0.001516659           1 -0.001516659           1
    ## 2 ENSMUSG00000025902 -0.227716550           1  0.227716550           1
    ## 3 ENSMUSG00000025903  0.021614261           1 -0.021614261           1
    ## 4 ENSMUSG00000033813  0.016960595           1 -0.016960595           1
    ## 5 ENSMUSG00000033845 -0.203318869           1  0.203318869           1
    ## 6 ENSMUSG00000051951  0.000000000           1  0.000000000           1

(Notice the difference in p values)

## 5.1 Automatic grouping of neighbourhoods

In many cases, such as this example, DA neighbourhoods are found in different areas of the KNN graph, and grouping together all significant DA populations might not be ideal, as they might include cells of very different celltypes. For this kind of scenario, we have implemented a neighbourhood function that uses community detection to partition neighbourhoods into groups on the basis of (1) the number of shared cells between 2 neighbourhoods; (2) the direction of fold-change for DA neighbourhoods; (3) the difference in fold change.

    ## Run buildNhoodGraph to store nhood adjacency matrix
    embryo_milo <- buildNhoodGraph(embryo_milo)

    ## Find groups
    da_results <- groupNhoods(embryo_milo, da_results, max.lfc.delta = 10)
    head(da_results)

    ##        logFC   logCPM         F       PValue          FDR Nhood   SpatialFDR
    ## 1  1.2248265 11.23671  1.315051 2.516854e-01 3.044581e-01     1 3.071792e-01
    ## 2  0.9786265 11.61182  1.167601 2.800878e-01 3.352114e-01     2 3.380802e-01
    ## 3 -2.6757417 11.59623 11.423364 7.459591e-04 1.854595e-03     3 1.797906e-03
    ## 4  1.5450770 11.40726  2.410157 1.207847e-01 1.566372e-01     4 1.584771e-01
    ## 5 -4.6765181 11.52996 26.184103 3.551589e-07 3.898086e-06     5 3.176566e-06
    ## 6 -5.1519344 10.99888 20.281286 7.261792e-06 4.299746e-05     6 3.692355e-05
    ##            celltype celltype_fraction NhoodGroup
    ## 1 Visceral endoderm         0.9824561          1
    ## 2      ExE ectoderm         1.0000000          2
    ## 3      ExE endoderm         1.0000000          3
    ## 4             Mixed         0.6315789          4
    ## 5  Primitive Streak         0.8082192          5
    ## 6  Primitive Streak         0.9807692          6

Let’s have a look at the detected groups

    plotNhoodGroups(embryo_milo, da_results, layout="umap")

    plotDAbeeswarm(da_results, "NhoodGroup")

We can easily check how changing the grouping parameters changes the groups we obtain, starting with the LFC delta by plotting with different values of `max.lfc.delta` (not executed here).

    # code not run - uncomment to run.
    # plotDAbeeswarm(groupNhoods(embryo_milo, da_results, max.lfc.delta = 1) , group.by = "NhoodGroup") + ggtitle("max LFC delta=1")
    # plotDAbeeswarm(groupNhoods(embryo_milo, da_results, max.lfc.delta = 2)   , group.by = "NhoodGroup") + ggtitle("max LFC delta=2")
    # plotDAbeeswarm(groupNhoods(embryo_milo, da_results, max.lfc.delta = 3)   , group.by = "NhoodGroup") + ggtitle("max LFC delta=3")

…and we can do the same for the minimum overlap between neighbourhoods… (code not executed).

    # code not run - uncomment to run.
    # plotDAbeeswarm(groupNhoods(embryo_milo, da_results, max.lfc.delta = 5, overlap=1) , group.by = "NhoodGroup") + ggtitle("overlap=5")
    # plotDAbeeswarm(groupNhoods(embryo_milo, da_results, max.lfc.delta = 5, overlap=5)   , group.by = "NhoodGroup") + ggtitle("overlap=10")
    # plotDAbeeswarm(groupNhoods(embryo_milo, da_results, max.lfc.delta = 5, overlap=10)   , group.by = "NhoodGroup") + ggtitle("overlap=20")

In these examples we settle for `overlap=5` and `max.lfc.delta=5`, as we need at least 2 neighbourhoods assigned to each group.

    set.seed(42)
    da_results <- groupNhoods(embryo_milo, da_results, max.lfc.delta = 10, overlap=1)
    plotNhoodGroups(embryo_milo, da_results, layout="umap")

    plotDAbeeswarm(da_results, group.by = "NhoodGroup")

## 5.2 Finding gene signatures for neighbourhoods

Once we have grouped neighbourhoods using `groupNhoods` we are now all set to identifying gene signatures between neighbourhood groups.

Let’s restrict the testing to highly variable genes in this case

    ## Exclude zero counts genes
    keep.rows <- rowSums(logcounts(embryo_milo)) != 0
    embryo_milo <- embryo_milo[keep.rows, ]

    ## Find HVGs
    set.seed(101)
    dec <- modelGeneVar(embryo_milo)
    hvgs <- getTopHVGs(dec, n=2000)

    # this vignette randomly fails to identify HVGs for some reason
    if(!length(hvgs)){
        set.seed(42)
        dec <- modelGeneVar(embryo_milo)
        hvgs <- getTopHVGs(dec, n=2000)
    }

    head(hvgs)

    ## [1] "ENSMUSG00000032083" "ENSMUSG00000095180" "ENSMUSG00000061808"
    ## [4] "ENSMUSG00000002985" "ENSMUSG00000024990" "ENSMUSG00000024391"

We run `findNhoodGroupMarkers` to test for one-vs-all differential gene expression for each neighbourhood group

    set.seed(42)
    nhood_markers <- findNhoodGroupMarkers(embryo_milo, da_results, subset.row = hvgs,
                                           aggregate.samples = TRUE, sample_col = "sample")

    head(nhood_markers)

    ##               GeneID    logFC_1 adj.P.Val_1    logFC_2 adj.P.Val_2     logFC_3
    ## 1 ENSMUSG00000000031  1.1062621   0.1909913  1.0877022  0.21352451  3.01690497
    ## 2 ENSMUSG00000000078  0.2400963   0.4584767 -0.1380247  0.66505457  0.01169928
    ## 3 ENSMUSG00000000088  0.3431289   0.2803619 -0.2366868  0.45458426  0.70527314
    ## 4 ENSMUSG00000000125 -0.1389530   0.3944875 -0.1638254  0.29623993  0.00862161
    ## 5 ENSMUSG00000000149  0.1384424   0.2403317 -0.1273906  0.28452288  0.26724756
    ## 6 ENSMUSG00000000184 -0.6763273   0.3069040 -1.1313969  0.06216331 -1.13557421
    ##    adj.P.Val_3     logFC_4 adj.P.Val_4     logFC_5 adj.P.Val_5    logFC_6
    ## 1 1.659245e-07 -1.60631861   0.1662209 -1.57298661 0.131846816 -1.6777606
    ## 2 9.633114e-01  0.11006856   0.7862189 -0.75937476 0.025877729 -0.2388328
    ## 3 2.737473e-03 -0.33896888   0.5116397 -0.28668887 0.453070042 -0.3740507
    ## 4 9.502122e-01  0.06612329   0.7472235  0.46211454 0.002973405 -0.1255959
    ## 5 2.462033e-03 -0.03614477   0.8143891 -0.10452632 0.467778591 -0.1275916
    ## 6 2.612023e-02  0.61432365   0.5287529  0.07766084 0.923822462 -0.4036482
    ##   adj.P.Val_6      logFC_7 adj.P.Val_7     logFC_8  adj.P.Val_8    logFC_9
    ## 1   0.1358704 -0.898493813  0.38880747  0.27954261 7.667095e-01 -0.3779684
    ## 2   0.5143002  0.001215968  0.99867260  0.01169174 9.697681e-01  1.1114333
    ## 3   0.3852606 -0.488150553  0.20725919  0.07314143 8.345319e-01  0.8972034
    ## 4   0.5039600  0.180619091  0.34302513 -0.11867377 4.955102e-01 -0.1969069
    ## 5   0.4212766 -0.086329679  0.54818469 -0.10064267 4.553629e-01  0.2517125
    ## 6   0.5761236  1.530766193  0.01585126  2.08107472 2.385153e-05 -1.6570115
    ##   adj.P.Val_9
    ## 1 0.783463000
    ## 2 0.000493266
    ## 3 0.012844624
    ## 4 0.360834092
    ## 5 0.085201902
    ## 6 0.030086914

Let’s check out the markers for group 5 for example

    gr5_markers <- nhood_markers[c("logFC_5", "adj.P.Val_5")]
    colnames(gr5_markers) <- c("logFC", "adj.P.Val")

    head(gr5_markers[order(gr5_markers$adj.P.Val), ])

    ##          logFC    adj.P.Val
    ## 591  0.8055467 2.657182e-08
    ## 146  0.5110828 2.449942e-06
    ## 982  0.6673730 2.449942e-06
    ## 646  1.9013006 7.480254e-06
    ## 200  0.7332162 8.459785e-06
    ## 1229 0.9750513 2.883711e-05

If you already know you are interested only in the markers for group 2, you might want to test just 8-VS-all using the `subset.groups` parameter:

    nhood_markers <- findNhoodGroupMarkers(embryo_milo, da_results, subset.row = hvgs,
                                           aggregate.samples = TRUE, sample_col = "sample",
                                           subset.groups = c("5")
                                           )

    head(nhood_markers)

    ##                      logFC_5  adj.P.Val_5             GeneID
    ## ENSMUSG00000024409 0.8055467 2.657182e-08 ENSMUSG00000024409
    ## ENSMUSG00000006445 0.5110828 2.449942e-06 ENSMUSG00000006445
    ## ENSMUSG00000029859 0.6673730 2.449942e-06 ENSMUSG00000029859
    ## ENSMUSG00000025219 1.9013006 7.480254e-06 ENSMUSG00000025219
    ## ENSMUSG00000012396 0.7332162 8.459785e-06 ENSMUSG00000012396
    ## ENSMUSG00000034336 0.9750513 2.883711e-05 ENSMUSG00000034336

You might also want to compare a subset of neighbourhoods between each other. You can specify the neighbourhoods to use for testing by setting the parameter `subset.nhoods`.

For example, you might want to compare just one pair of neighbourhood groups against each other:

    nhood_markers <- findNhoodGroupMarkers(embryo_milo, da_results, subset.row = hvgs,
                                           subset.nhoods = da_results$NhoodGroup %in% c('5','6'),
                                           aggregate.samples = TRUE, sample_col = "sample")

    ## Warning: Zero sample variances detected, have been offset away from zero
    ## Warning: Zero sample variances detected, have been offset away from zero

    head(nhood_markers)

    ##               GeneID     logFC_5 adj.P.Val_5     logFC_6 adj.P.Val_6
    ## 1 ENSMUSG00000000031 -0.00891519  0.95562591  0.00891519  0.95562591
    ## 2 ENSMUSG00000000078 -0.41433909  0.25765293  0.41433909  0.25765293
    ## 3 ENSMUSG00000000088  0.06774081  0.89898292 -0.06774081  0.89898292
    ## 4 ENSMUSG00000000125  0.43656169  0.04675841 -0.43656169  0.04675841
    ## 5 ENSMUSG00000000149 -0.05213213  0.78295089  0.05213213  0.78295089
    ## 6 ENSMUSG00000000184  0.54096619  0.22079362 -0.54096619  0.22079362

or you might use `subset.nhoods` to exclude singleton neighbourhoods, or to subset to the neighbourhoods that show significant DA.

## 5.3 Visualize detected markers

Lets select marker genes for group 10 at FDR 1% and log-fold-Change > 1.

    ggplot(nhood_markers, aes(logFC_5, -log10(adj.P.Val_5 ))) +
      geom_point(alpha=0.5, size=0.5) +
      geom_hline(yintercept = 3)

    markers <- nhood_markers$GeneID[nhood_markers$adj.P.Val_5 < 0.01 & nhood_markers$logFC_5 > 0]

We can visualize the expression in neighbourhoods using `plotNhoodExpressionGroups`.

    set.seed(42)
    plotNhoodExpressionGroups(embryo_milo, da_results, features=intersect(rownames(embryo_milo), markers[1:10]),
                              subset.nhoods = da_results$NhoodGroup %in% c('6','5'),
                              scale=TRUE,
                              grid.space = "fixed")

    ## Warning in plotNhoodExpressionGroups(embryo_milo, da_results, features =
    ## intersect(rownames(embryo_milo), : Nothing in nhoodExpression(x): computing for
    ## requested features...

## 5.4 DGE testing within a group

In some cases you might want to test for differential expression between cells in different conditions within the same neighbourhood group. You can do that using `testDiffExp`:

    dge_6 <- testDiffExp(embryo_milo, da_results, design = ~ stage, meta.data = data.frame(colData(embryo_milo)),
                         subset.row = rownames(embryo_milo)[1:5], subset.nhoods=da_results$NhoodGroup=="6")

    dge_6

    ## $`6`
    ##                           logFC      AveExpr         t      P.Value   adj.P.Val
    ## ENSMUSG00000033845 -0.129562967 2.4572848555 -3.534184 0.0004194765 0.002097383
    ## ENSMUSG00000051951  0.002606210 0.0007186177  1.483146 0.1382126241 0.345531560
    ## ENSMUSG00000025902  0.008385242 0.0198825714  1.056392 0.2909325956 0.484887659
    ## ENSMUSG00000102343  0.000000000 0.0000000000  0.000000 1.0000000000 1.000000000
    ## ENSMUSG00000025900  0.000000000 0.0000000000  0.000000 1.0000000000 1.000000000
    ##                             B Nhood.Group
    ## ENSMUSG00000033845  -7.857354           6
    ## ENSMUSG00000051951 -12.984483           6
    ## ENSMUSG00000025902 -13.526162           6
    ## ENSMUSG00000102343 -14.084282           6
    ## ENSMUSG00000025900 -14.084282           6

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] MouseGastrulationData_1.23.0 SpatialExperiment_1.19.1
    ##  [3] MouseThymusAgeing_1.17.0     patchwork_1.3.0
    ##  [5] dplyr_1.1.4                  scran_1.37.0
    ##  [7] scater_1.37.0                ggplot2_3.5.2
    ##  [9] scuttle_1.19.0               SingleCellExperiment_1.31.0
    ## [11] SummarizedExperiment_1.39.0  Biobase_2.69.0
    ## [13] GenomicRanges_1.61.0         GenomeInfoDb_1.45.4
    ## [15] IRanges_2.43.0               S4Vectors_0.47.0
    ## [17] BiocGenerics_0.55.0          generics_0.1.4
    ## [19] MatrixGenerics_1.21.0        matrixStats_1.5.0
    ## [21] miloR_2.5.1                  edgeR_4.7.2
    ## [23] 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] rjson_0.2.23         bluster_1.19.0       gtools_3.9.5
    ##  [55] tools_4.5.0          vipor_0.4.7          beeswarm_0.4.0
    ##  [58] glue_1.8.0           grid_4.5.0           cluster_2.1.8.1
    ##  [61] gtable_0.3.6         tidyr_1.3.1          BiocSingular_1.25.0
    ##  [64] tidygraph_1.3.1      ScaledMatrix_1.17.0  metapod_1.17.0
    ##  [67] XVector_0.49.0       RcppAnnoy_0.0.22     ggrepel_0.9.6
    ##  [70] BiocVersion_3.22.0   pillar_1.10.2        stringr_1.5.1
    ##  [73] BumpyMatrix_1.17.0   splines_4.5.0        tweenr_2.0.3
    ##  [76] BiocFileCache_2.99.5 lattice_0.22-7       FNN_1.1.4.1
    ##  [79] bit_4.6.0            tidyselect_1.2.1     locfit_1.5-9.12
    ##  [82] Biostrings_2.77.1    knitr_1.50           gridExtra_2.3
    ##  [85] bookdown_0.43        xfun_0.52            graphlayouts_1.2.2
    ##  [88] statmod_1.5.0        stringi_1.8.7        UCSC.utils_1.5.0
    ##  [91] yaml_2.3.10          evaluate_1.0.3       codetools_0.2-20
    ##  [94] ggraph_2.2.1         tibble_3.2.1         BiocManager_1.30.25
    ##  [97] cli_3.6.5            uwot_0.2.3           jquerylib_0.1.4
    ## [100] dichromat_2.0-0.1    Rcpp_1.0.14          dbplyr_2.5.0
    ## [103] png_0.1-8            parallel_4.5.0       blob_1.2.4
    ## [106] viridisLite_0.4.2    scales_1.4.0         purrr_1.0.4
    ## [109] crayon_1.5.3         rlang_1.1.6          cowplot_1.1.3
    ## [112] KEGGREST_1.49.0