Date: 2026-04-28

# Flexible clustering for Bioconductor

Aaron Lun*

*infinite.monkeys.with.keyboards@gmail.com

#### 28 April 2026

#### Package

bluster 1.22.0

# Contents

# 1 Introduction

The bluster package provides a flexible and extensible framework for clustering in Bioconductor packages/workflows. At its core is the `clusterRows()` generic that controls dispatch to different clustering algorithms. We will demonstrate on some single-cell RNA sequencing data from the scRNAseq package; our aim is to cluster cells into cell populations based on their PC coordinates.

    library(scRNAseq)
    sce <- ZeiselBrainData()

    # Trusting the authors' quality control, and going straight to normalization.
    library(scuttle)
    sce <- logNormCounts(sce)

    ## Warning in .library_size_factors(assay(x, assay.type), ...): 'librarySizeFactors' is deprecated.
    ## Use 'scrapper::centerSizeFactors' instead.
    ## See help("Deprecated")

    ## Warning in .local(x, ...): 'normalizeCounts' is deprecated.
    ## Use 'scrapper::normalizeCounts' instead.
    ## See help("Deprecated")

    # Feature selection based on highly variable genes.
    library(scran)
    dec <- modelGeneVar(sce)

    ## Warning in fitTrendVar(fm, fv, ...): 'fitTrendVar' is deprecated.
    ## Use 'scrapper::fitVarianceTrend' instead.
    ## See help("Deprecated")

    ## Warning in combineBlocks(collected, method = method, equiweight = equiweight, : 'combineBlocks' is deprecated.
    ## See help("Deprecated")

    hvgs <- getTopHVGs(dec, n=1000)

    ## Warning in getTopHVGs(dec, n = 1000): 'getTopHVGs' is deprecated.
    ## Use 'scrapper::chooseHighlyVariableGenes' instead.
    ## See help("Deprecated")

    # Dimensionality reduction for work (PCA) and pleasure (t-SNE).
    set.seed(1000)
    library(scater)
    sce <- runPCA(sce, ncomponents=20, subset_row=hvgs)
    sce <- runUMAP(sce, dimred="PCA")

    mat <- reducedDim(sce, "PCA")
    dim(mat)

    ## [1] 3005   20

# 2 Based on distance matrices

## 2.1 Hierarchical clustering

Our first algorithm is good old hierarchical clustering, as implemented using `hclust()` from the stats package. This automatically sets the cut height to half the dendrogram height.

    library(bluster)
    hclust.out <- clusterRows(mat, HclustParam())
    plotUMAP(sce, colour_by=I(hclust.out))

Advanced users can achieve greater control of the procedure by passing more parameters to the `HclustParam()` constructor. Here, we use Ward’s criterion for the agglomeration with a dynamic tree cut from the dynamicTreeCut package.

    hp2 <- HclustParam(method="ward.D2", cut.dynamic=TRUE)
    hp2

    ## class: HclustParam
    ## metric: [default]
    ## method: ward.D2
    ## cut.fun: cutreeDynamic
    ## cut.params(0):
    ## dist.fun: stats::dist
    ## clust.fun: stats::hclust

    hclust.out <- clusterRows(mat, hp2)
    plotUMAP(sce, colour_by=I(hclust.out))

## 2.2 Affinity propagation

Another option is to use affinity propagation, as implemented using the apcluster package. Here, messages are passed between observations to decide on a set of exemplars, each of which form the center of a cluster.

This is not particularly fast as it involves the calculation of a square similarity matrix between all pairs of observations. So, we’ll speed it up by taking analyzing a subset of the data:

    set.seed(1000)
    sub <- sce[,sample(ncol(sce), 200)]
    ap.out <- clusterRows(reducedDim(sub), AffinityParam())
    plotUMAP(sub, colour_by=I(ap.out))

The `q` parameter is probably the most important and determines the resolution of the clustering. This can be set to any value below 1, with smaller (possibly negative) values corresponding to coarser clusters.

    set.seed(1000)
    ap.out <- clusterRows(reducedDim(sub), AffinityParam(q=-2))
    plotUMAP(sub, colour_by=I(ap.out))

# 3 With a fixed number of clusters

## 3.1 \(k\)-means clustering

A classic algorithm is \(k\)-means clustering, as implemented using the `kmeans()` function. This requires us to pass in the number of clusters, either as a number:

    set.seed(100)
    kmeans.out <- clusterRows(mat, KmeansParam(10))
    plotUMAP(sce, colour_by=I(kmeans.out))

Or as a function of the number of observations, which is useful for vector quantization purposes:

    kp <- KmeansParam(sqrt)
    kp

    ## class: KmeansParam
    ## centers: variable
    ## iter.max: 10
    ## nstart: 1
    ## algorithm: Hartigan-Wong

    set.seed(100)
    kmeans.out <- clusterRows(mat, kp)
    plotUMAP(sce, colour_by=I(kmeans.out))

A variant of this approach is mini-batch \(k\)-means, as implemented in the mbkmeans package. This uses mini-batching to approximate the full \(k\)-means algorithm for greater speed.

    set.seed(100)
    mbkmeans.out <- clusterRows(mat, MbkmeansParam(20))
    plotUMAP(sce, colour_by=I(mbkmeans.out))

## 3.2 Self-organizing maps

We can also use self-organizing maps (SOMs) from the kohonen package. This allocates observations to nodes of a simple neural network; each node is then treated as a cluster.

    set.seed(1000)
    som.out <- clusterRows(mat, SomParam(20))
    plotUMAP(sce, colour_by=I(som.out))

The key feature of SOMs is that they apply additional topological constraints on the relative positions of the nodes. This allows us to naturally determine the relationships between clusters based on the proximity of the nodes.

    set.seed(1000)
    som.out <- clusterRows(mat, SomParam(100), full=TRUE)

    par(mfrow=c(1,2))
    plot(som.out$objects$som, "counts")
    grid <- som.out$objects$som$grid$pts
    text(grid[,1], grid[,2], seq_len(nrow(grid)))

# 4 Graph-based clustering

We can build shared or direct nearest neighbor graphs and perform community detection with igraph. Here, the number of neighbors `k` controls the resolution of the clusters.

    set.seed(101) # just in case there are ties.
    graph.out <- clusterRows(mat, NNGraphParam(k=10))
    plotUMAP(sce, colour_by=I(graph.out))

It is again straightforward to tune the procedure by passing more arguments such as the community detection algorithm to use.

    set.seed(101) # just in case there are ties.
    np <- NNGraphParam(k=20, cluster.fun="louvain")
    np

    ## class: SNNGraphParam
    ## k: 20
    ## type: rank
    ## BNPARAM: KmknnParam
    ## num.threads: 1
    ## cluster.fun: louvain
    ## cluster.args(0):

    graph.out <- clusterRows(mat, np)
    plotUMAP(sce, colour_by=I(graph.out))

# 5 Density-based clustering

We also implement a version of the DBSCAN algorithm for density-based clustering. This focuses on identifying masses of continuous density.

    dbscan.out <- clusterRows(mat, DbscanParam())
    plotUMAP(sce, colour_by=I(dbscan.out))

Unlike the other methods, it will consider certain points to be noise and discard them from the output.

    summary(is.na(dbscan.out))

    ##    Mode   FALSE    TRUE
    ## logical    1789    1216

The resolution of the clustering can be modified by tinkering with the `core.prop`. Smaller values will generally result in smaller clusters as well as more noise points.

    dbscan.out <- clusterRows(mat, DbscanParam(core.prop=0.1))
    summary(is.na(dbscan.out))

    ##    Mode   FALSE    TRUE
    ## logical     565    2440

# 6 Two-phase clustering

We also provide a wrapper for a hybrid “two-step” approach for handling larger datasets. Here, a fast agglomeration is performed with \(k\)-means to compact the data, followed by a slower graph-based clustering step to obtain interpretable meta-clusters. (This dataset is not, by and large, big enough for this approach to work particularly well.)

    set.seed(100) # for the k-means
    two.out <- clusterRows(mat, TwoStepParam())
    plotUMAP(sce, colour_by=I(two.out))

Each step is itself parametrized by `BlusterParam` objects, so it is possible to tune them individually:

    twop <- TwoStepParam(second=NNGraphParam(k=5))
    twop

    ## class: TwoStepParam
    ## first:
    ##   class: KmeansParam
    ##   centers: variable
    ##   iter.max: 10
    ##   nstart: 1
    ##   algorithm: Hartigan-Wong
    ## second:
    ##   class: SNNGraphParam
    ##   k: 5
    ##   type: rank
    ##   BNPARAM: KmknnParam
    ##   num.threads: 1
    ##   cluster.fun: walktrap
    ##   cluster.args(0):

    set.seed(100) # for the k-means
    two.out <- clusterRows(mat, TwoStepParam())
    plotUMAP(sce, colour_by=I(two.out))

# 7 Obtaining full clustering statistics

Sometimes the vector of cluster assignments is not enough. We can obtain more information about the clustering procedure by setting `full=TRUE` in `clusterRows()`. For example, we could obtain the actual graph generated by `NNGraphParam()`:

    nn.out <- clusterRows(mat, NNGraphParam(), full=TRUE)
    nn.out$objects$graph

    ## IGRAPH 4eb6eed U-W- 3005 87028 --
    ## + attr: weight (e/n)
    ## + edges from 4eb6eed:
    ##  [1]  1-- 2  1-- 3  2-- 3  1-- 4  2-- 4  3-- 4  4-- 5  1-- 5  2-- 5  3-- 5
    ## [11]  1-- 6  2-- 6  3-- 6  4-- 6  5-- 6  1-- 7  5-- 7  6-- 7  2-- 7  4-- 7
    ## [21]  3-- 7  3-- 8  1-- 8  2-- 8  4-- 8  6-- 8  7-- 8  5-- 8  1-- 9  2-- 9
    ## [31]  4-- 9  5-- 9  7-- 9  3-- 9  6-- 9  8-- 9  1--10  5--10  9--10  3--10
    ## [41]  4--10  3--11  9--11 10--11  1--11  5--11  2--13  5--13  6--13  7--13
    ## [51] 12--13  8--13 12--14 13--14 12--15 13--15 14--15  2--15  5--15  6--15
    ## [61]  7--15 12--16 13--16 14--16 15--16 14--17 12--17 15--17 16--17 13--17
    ## [71] 12--18 14--18 15--18 16--18 13--18 17--18 19--20 12--20 14--20 15--20
    ## + ... omitted several edges

The assignment vector is still reported in the `clusters` entry:

    table(nn.out$clusters)

    ##
    ##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19
    ## 166 216 256 543 218  89 583  92 123 186  91  42  94  64  58  58  60  35  31

# 8 Further comments

`clusterRows()` enables users or developers to easily switch between clustering algorithms by changing a single argument. Indeed, by passing the `BlusterParam` object across functions, we can ensure that the same algorithm is used through a workflow. It is also helpful for package functions as it provides diverse functionality without compromising a clean function signature. However, the true power of this framework lies in its extensibility. Anyone can write a `clusterRows()` method for a new clustering algorithm with an associated `BlusterParam` subclass, and that procedure is immediately compatible with any workflow or function that was already using `clusterRows()`.

# Session information

    sessionInfo()

    ## R version 4.6.0 Patched (2026-04-24 r89963)
    ## Platform: aarch64-apple-darwin23
    ## Running under: macOS Tahoe 26.3.1
    ##
    ## Matrix products: default
    ## BLAS:   /Library/Frameworks/R.framework/Versions/4.6/Resources/lib/libRblas.0.dylib
    ## LAPACK: /Library/Frameworks/R.framework/Versions/4.6/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.1
    ##
    ## locale:
    ## [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
    ##
    ## 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] bluster_1.22.0              scater_1.40.0
    ##  [3] ggplot2_4.0.3               scran_1.40.0
    ##  [5] scuttle_1.22.0              scRNAseq_2.25.0
    ##  [7] SingleCellExperiment_1.34.0 SummarizedExperiment_1.42.0
    ##  [9] Biobase_2.72.0              GenomicRanges_1.64.0
    ## [11] Seqinfo_1.2.0               IRanges_2.46.0
    ## [13] S4Vectors_0.50.0            BiocGenerics_0.58.0
    ## [15] generics_0.1.4              MatrixGenerics_1.24.0
    ## [17] matrixStats_1.5.0           BiocStyle_2.40.0
    ##
    ## loaded via a namespace (and not attached):
    ##   [1] BiocIO_1.22.0            bitops_1.0-9             filelock_1.0.3
    ##   [4] tibble_3.3.1             XML_3.99-0.23            lifecycle_1.0.5
    ##   [7] httr2_1.2.2              edgeR_4.10.0             doParallel_1.0.17
    ##  [10] lattice_0.22-9           ensembldb_2.36.0         alabaster.base_1.12.0
    ##  [13] magrittr_2.0.5           limma_3.68.0             sass_0.4.10
    ##  [16] rmarkdown_2.31           jquerylib_0.1.4          yaml_2.3.12
    ##  [19] metapod_1.20.0           otel_0.2.0               cowplot_1.2.0
    ##  [22] DBI_1.3.0                RColorBrewer_1.1-3       abind_1.4-8
    ##  [25] AnnotationFilter_1.36.0  RCurl_1.98-1.18          rappdirs_0.3.4
    ##  [28] ggrepel_0.9.8            irlba_2.3.7              kohonen_3.0.13
    ##  [31] alabaster.sce_1.12.0     RSpectra_0.16-2          dqrng_0.4.1
    ##  [34] codetools_0.2-20         DelayedArray_0.38.0      tidyselect_1.2.1
    ##  [37] UCSC.utils_1.8.0         farver_2.1.2             gmp_0.7-5.1
    ##  [40] ScaledMatrix_1.20.0      viridis_0.6.5            BiocFileCache_3.2.0
    ##  [43] dynamicTreeCut_1.63-1    GenomicAlignments_1.48.0 jsonlite_2.0.0
    ##  [46] BiocNeighbors_2.6.0      iterators_1.0.14         foreach_1.5.2
    ##  [49] tools_4.6.0              Rcpp_1.1.1-1.1           glue_1.8.1
    ##  [52] gridExtra_2.3            SparseArray_1.12.0       xfun_0.57
    ##  [55] GenomeInfoDb_1.48.0      dplyr_1.2.1              HDF5Array_1.40.0
    ##  [58] gypsum_1.8.0             withr_3.0.2              BiocManager_1.30.27
    ##  [61] fastmap_1.2.0            rhdf5filters_1.24.0      digest_0.6.39
    ##  [64] rsvd_1.0.5               R6_2.6.1                 dichromat_2.0-0.1
    ##  [67] RSQLite_2.4.6            cigarillo_1.2.0          h5mread_1.4.0
    ##  [70] rtracklayer_1.72.0       FNN_1.1.4.1              httr_1.4.8
    ##  [73] S4Arrays_1.12.0          uwot_0.2.4               pkgconfig_2.0.3
    ##  [76] gtable_0.3.6             blob_1.3.0               S7_0.2.2
    ##  [79] XVector_0.52.0           htmltools_0.5.9          bookdown_0.46
    ##  [82] ProtGenerics_1.44.0      scales_1.4.0             alabaster.matrix_1.12.0
    ##  [85] ClusterR_1.3.6           png_0.1-9                knitr_1.51
    ##  [88] rjson_0.2.23             curl_7.1.0               cachem_1.1.0
    ##  [91] rhdf5_2.56.0             BiocVersion_3.23.1       parallel_4.6.0
    ##  [94] vipor_0.4.7              AnnotationDbi_1.74.0     restfulr_0.0.16
    ##  [97] pillar_1.11.1            grid_4.6.0               alabaster.schemas_1.12.0
    ## [100] vctrs_0.7.3              BiocSingular_1.28.0      dbplyr_2.5.2
    ## [103] beachmat_2.28.0          cluster_2.1.8.2          beeswarm_0.4.0
    ## [106] evaluate_1.0.5           tinytex_0.59             GenomicFeatures_1.64.0
    ## [109] magick_2.9.1             cli_3.6.6                locfit_1.5-9.12
    ## [112] compiler_4.6.0           Rsamtools_2.28.0         rlang_1.2.0
    ## [115] crayon_1.5.3             mbkmeans_1.28.0          labeling_0.4.3
    ## [118] ggbeeswarm_0.7.3         alabaster.se_1.12.0      viridisLite_0.4.3
    ## [121] BiocParallel_1.46.0      Biostrings_2.80.0        lazyeval_0.2.3
    ## [124] Matrix_1.7-5             ExperimentHub_3.2.0      benchmarkme_1.0.8
    ## [127] bit64_4.8.0              Rhdf5lib_2.0.0           KEGGREST_1.52.0
    ## [130] statmod_1.5.1            alabaster.ranges_1.12.0  apcluster_1.4.14
    ## [133] AnnotationHub_4.2.0      igraph_2.3.0             memoise_2.0.1
    ## [136] bslib_0.10.0             benchmarkmeData_2.0.0    bit_4.6.0