# Modeling continuous cell-level covariates

### Collapse using mean value for pseudobulk data

Developed by [Gabriel Hoffman](http://gabrielhoffman.github.io/)

#### Run on 2025-04-15 20:21:11

# 1 Introduction

Since read counts are summed across cells in a pseudobulk approach, modeling continuous cell-level covariates also requires a collapsing step. Here we summarize the values of a variable from a set of cells using the mean, and store the value for each cell type. Including these variables in a regression formula uses the summarized values from the corresponding cell type.

We demonstrate this feature on a lightly modified analysis of PBMCs from 8 individuals stimulated with interferon-β (Kang, et al, 2018, Nature Biotech).

# 2 Standard processing

Here is the code from the main vignette:

    library(dreamlet)
    library(muscat)
    library(ExperimentHub)
    library(scater)

    # Download data, specifying EH2259 for the Kang, et al study
    eh <- ExperimentHub()
    sce <- eh[["EH2259"]]

    # only keep singlet cells with sufficient reads
    sce <- sce[rowSums(counts(sce) > 0) > 0, ]
    sce <- sce[, colData(sce)$multiplets == "singlet"]

    # compute QC metrics
    qc <- perCellQCMetrics(sce)

    # remove cells with few or many detected genes
    ol <- isOutlier(metric = qc$detected, nmads = 2, log = TRUE)
    sce <- sce[, !ol]

    # set variable indicating stimulated (stim) or control (ctrl)
    sce$StimStatus <- sce$stim

In many datasets, continuous cell-level variables could be mapped reads, gene count, mitochondrial rate, etc. There are no continuous cell-level variables in this dataset, so we can simulate two from a normal distribution:

    sce$value1 <- rnorm(ncol(sce))
    sce$value2 <- rnorm(ncol(sce))

# 3 Pseudobulk

Now compute the pseudobulk using standard code:

    sce$id <- paste0(sce$StimStatus, sce$ind)

    # Create pseudobulk
    pb <- aggregateToPseudoBulk(sce,
      assay = "counts",
      cluster_id = "cell",
      sample_id = "id",
      verbose = FALSE
    )

The means per variable, cell type, and sample are stored in the pseudobulk `SingleCellExperiment` object:

    metadata(pb)$aggr_means

    ## # A tibble: 128 × 5
    ## # Groups:   cell [8]
    ##    cell    id       cluster   value1   value2
    ##    <fct>   <fct>      <dbl>    <dbl>    <dbl>
    ##  1 B cells ctrl101     3.96  0.0825  -0.0472
    ##  2 B cells ctrl1015    4.00 -0.0688  -0.0103
    ##  3 B cells ctrl1016    4     0.00908  0.257
    ##  4 B cells ctrl1039    4.04  0.0706   0.0861
    ##  5 B cells ctrl107     4    -0.0719  -0.0936
    ##  6 B cells ctrl1244    4     0.0689   0.0820
    ##  7 B cells ctrl1256    4.01 -0.119   -0.0323
    ##  8 B cells ctrl1488    4.02 -0.00105  0.0237
    ##  9 B cells stim101     4.09 -0.196   -0.0906
    ## 10 B cells stim1015    4.06  0.0675   0.00598
    ## # ℹ 118 more rows

# 4 Analysis

Including these variables in a regression formula uses the summarized values from the corresponding cell type. This happens behind the scenes, so the user doesn’t need to distinguish bewteen sample-level variables stored in `colData(pb)` and cell-level variables stored in `metadata(pb)$aggr_means`.

Variance partition and hypothesis testing proceeds as ususal:

    form <- ~ StimStatus + value1 + value2

    # Normalize and apply voom/voomWithDreamWeights
    res.proc <- processAssays(pb, form, min.count = 5)

    # run variance partitioning analysis
    vp.lst <- fitVarPart(res.proc, form)

    # Summarize variance fractions genome-wide for each cell type
    plotVarPart(vp.lst, label.angle = 60)

    # Differential expression analysis within each assay
    res.dl <- dreamlet(res.proc, form)

    # dreamlet results include coefficients for value1 and value2
    res.dl

    ## class: dreamletResult
    ## assays(8): B cells CD14+ Monocytes ... Megakaryocytes NK cells
    ## Genes:
    ##  min: 164
    ##  max: 5262
    ## details(7): assay n_retain ... n_errors error_initial
    ## coefNames(4): (Intercept) StimStatusstim value1 value2

# 5 Details

A variable in `colData(sce)` is handled according to if the variable is

- continuous: the mean per donor/cell type is stored in `metadata(pb)$aggr_means`
- discrete
  - [constant within each donor/cell type] it is stored in `colData(pb)`
  - [varies within each donor/cell type] there is no good way to summarize it. The variable is dropped.

# 6 Session Info

    ## R version 4.5.0 RC (2025-04-04 r88126 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] muscData_1.21.0             scater_1.36.0
    ##  [3] scuttle_1.18.0              ExperimentHub_2.16.0
    ##  [5] AnnotationHub_3.16.0        BiocFileCache_2.16.0
    ##  [7] dbplyr_2.5.0                muscat_1.22.0
    ##  [9] dreamlet_1.6.0              SingleCellExperiment_1.30.0
    ## [11] SummarizedExperiment_1.38.0 Biobase_2.68.0
    ## [13] GenomicRanges_1.60.0        GenomeInfoDb_1.44.0
    ## [15] IRanges_2.42.0              S4Vectors_0.46.0
    ## [17] BiocGenerics_0.54.0         generics_0.1.3
    ## [19] MatrixGenerics_1.20.0       matrixStats_1.5.0
    ## [21] variancePartition_1.38.0    BiocParallel_1.42.0
    ## [23] limma_3.64.0                ggplot2_3.5.2
    ## [25] BiocStyle_2.36.0
    ##
    ## loaded via a namespace (and not attached):
    ##   [1] bitops_1.0-9              httr_1.4.7
    ##   [3] RColorBrewer_1.1-3        doParallel_1.0.17
    ##   [5] Rgraphviz_2.52.0          numDeriv_2016.8-1.1
    ##   [7] sctransform_0.4.1         tools_4.5.0
    ##   [9] backports_1.5.0           utf8_1.2.4
    ##  [11] R6_2.6.1                  metafor_4.8-0
    ##  [13] mgcv_1.9-3                GetoptLong_1.0.5
    ##  [15] withr_3.0.2               prettyunits_1.2.0
    ##  [17] gridExtra_2.3             cli_3.6.4
    ##  [19] sandwich_3.1-1            labeling_0.4.3
    ##  [21] sass_0.4.10               KEGGgraph_1.68.0
    ##  [23] SQUAREM_2021.1            mvtnorm_1.3-3
    ##  [25] blme_1.0-6                mixsqp_0.3-54
    ##  [27] zenith_1.10.0             parallelly_1.43.0
    ##  [29] invgamma_1.1              RSQLite_2.3.9
    ##  [31] shape_1.4.6.1             gtools_3.9.5
    ##  [33] dplyr_1.1.4               Matrix_1.7-3
    ##  [35] metadat_1.4-0             ggbeeswarm_0.7.2
    ##  [37] abind_1.4-8               lifecycle_1.0.4
    ##  [39] multcomp_1.4-28           yaml_2.3.10
    ##  [41] edgeR_4.6.0               mathjaxr_1.6-0
    ##  [43] gplots_3.2.0              SparseArray_1.8.0
    ##  [45] grid_4.5.0                blob_1.2.4
    ##  [47] crayon_1.5.3              lattice_0.22-7
    ##  [49] beachmat_2.24.0           msigdbr_10.0.2
    ##  [51] annotate_1.86.0           KEGGREST_1.48.0
    ##  [53] magick_2.8.6              pillar_1.10.2
    ##  [55] knitr_1.50                ComplexHeatmap_2.24.0
    ##  [57] rjson_0.2.23              boot_1.3-31
    ##  [59] estimability_1.5.1        corpcor_1.6.10
    ##  [61] future.apply_1.11.3       codetools_0.2-20
    ##  [63] glue_1.8.0                data.table_1.17.0
    ##  [65] vctrs_0.6.5               png_0.1-8
    ##  [67] Rdpack_2.6.4              gtable_0.3.6
    ##  [69] assertthat_0.2.1          cachem_1.1.0
    ##  [71] zigg_0.0.2                xfun_0.52
    ##  [73] mime_0.13                 rbibutils_2.3
    ##  [75] S4Arrays_1.8.0            Rfast_2.1.5.1
    ##  [77] coda_0.19-4.1             reformulas_0.4.0
    ##  [79] survival_3.8-3            iterators_1.0.14
    ##  [81] tinytex_0.57              statmod_1.5.0
    ##  [83] TH.data_1.1-3             nlme_3.1-168
    ##  [85] pbkrtest_0.5.3            bit64_4.6.0-1
    ##  [87] filelock_1.0.3            progress_1.2.3
    ##  [89] EnvStats_3.0.0            bslib_0.9.0
    ##  [91] TMB_1.9.17                irlba_2.3.5.1
    ##  [93] vipor_0.4.7               KernSmooth_2.23-26
    ##  [95] colorspace_2.1-1          rmeta_3.0
    ##  [97] DBI_1.2.3                 DESeq2_1.48.0
    ##  [99] tidyselect_1.2.1          emmeans_1.11.0
    ## [101] curl_6.2.2                bit_4.6.0
    ## [103] compiler_4.5.0            graph_1.86.0
    ## [105] BiocNeighbors_2.2.0       DelayedArray_0.34.0
    ## [107] bookdown_0.43             scales_1.3.0
    ## [109] caTools_1.18.3            remaCor_0.0.18
    ## [111] rappdirs_0.3.3            stringr_1.5.1
    ## [113] digest_0.6.37             minqa_1.2.8
    ## [115] rmarkdown_2.29            aod_1.3.3
    ## [117] XVector_0.48.0            RhpcBLASctl_0.23-42
    ## [119] htmltools_0.5.8.1         pkgconfig_2.0.3
    ## [121] lme4_1.1-37               sparseMatrixStats_1.20.0
    ## [123] mashr_0.2.79              fastmap_1.2.0
    ## [125] rlang_1.1.6               GlobalOptions_0.1.2
    ## [127] UCSC.utils_1.4.0          DelayedMatrixStats_1.30.0
    ## [129] farver_2.1.2              jquerylib_0.1.4
    ## [131] zoo_1.8-14                jsonlite_2.0.0
    ## [133] BiocSingular_1.24.0       RCurl_1.98-1.17
    ## [135] magrittr_2.0.3            GenomeInfoDbData_1.2.14
    ## [137] munsell_0.5.1             Rcpp_1.0.14
    ## [139] babelgene_22.9            viridis_0.6.5
    ## [141] EnrichmentBrowser_2.38.0  stringi_1.8.7
    ## [143] MASS_7.3-65               plyr_1.8.9
    ## [145] listenv_0.9.1             parallel_4.5.0
    ## [147] ggrepel_0.9.6             Biostrings_2.76.0
    ## [149] splines_4.5.0             hms_1.1.3
    ## [151] circlize_0.4.16           locfit_1.5-9.12
    ## [153] reshape2_1.4.4            ScaledMatrix_1.16.0
    ## [155] BiocVersion_3.21.1        XML_3.99-0.18
    ## [157] evaluate_1.0.3            RcppParallel_5.1.10
    ## [159] BiocManager_1.30.25       nloptr_2.2.1
    ## [161] foreach_1.5.2             tidyr_1.3.1
    ## [163] purrr_1.0.4               future_1.40.0
    ## [165] clue_0.3-66               scattermore_1.2
    ## [167] ashr_2.2-63               rsvd_1.0.5
    ## [169] broom_1.0.8               xtable_1.8-4
    ## [171] fANCOVA_0.6-1             viridisLite_0.4.2
    ## [173] truncnorm_1.0-9           tibble_3.2.1
    ## [175] lmerTest_3.1-3            glmmTMB_1.1.11
    ## [177] memoise_2.0.1             beeswarm_0.4.0
    ## [179] AnnotationDbi_1.70.0      cluster_2.1.8.1
    ## [181] globals_0.16.3            GSEABase_1.70.0