-
Notifications
You must be signed in to change notification settings - Fork 4
/
differential_discovery.R
2068 lines (1940 loc) · 90.7 KB
/
differential_discovery.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# differential_discovery.R
# This file contains functions relevant to performing differential discovery
# analyses (differential abundance analysis and differential expression analysis)
# on tof_tbl objects containing high-dimensional cytometry data.
# diffcyt ----------------------------------------------------------------------
#' Differential Abundance Analysis (DAA) with diffcyt
#'
#' This function performs differential abundance analysis on the cell clusters
#' contained within a `tof_tbl` using one of three
#' methods implemented in the \href{https://www.bioconductor.org/packages/release/bioc/html/diffcyt.html}{diffcyt}
#' package for differential discovery analysis in high-dimensional cytometry
#' data.
#'
#' The three methods are based on generalized linear mixed models ("glmm"),
#' \href{https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2796818/}{edgeR} ("edgeR"), and
#' \href{https://genomebiology.biomedcentral.com/articles/10.1186/gb-2014-15-2-r29}{voom} ("voom").
#' While both the "glmm" and "voom" methods can model both fixed effects and random
#' effects, the "edgeR" method can only model fixed effects.
#'
#' @param tof_tibble A `tof_tbl` or a `tibble`.
#'
#' @param sample_col An unquoted column name indicating which column in `tof_tibble`
#' represents the id of the sample from which each cell was collected. `sample_col`
#' should serve as a unique identifier for each sample collected during data acquisition -
#' all cells with the same value for `sample_col` will be treated as a part of the same
#' observational unit.
#'
#' @param cluster_col An unquoted column name indicating which column in `tof_tibble`
#' stores the cluster ids of the cluster to which each cell belongs.
#' Cluster labels can be produced via any method the user chooses - including manual gating,
#' any of the functions in the `tof_cluster_*` function family, or any other method.
#'
#' @param fixed_effect_cols Unquoted column names representing which columns in
#' `tof_tibble` should be used to model fixed effects during the differential
#' abundance analysis. Generally speaking, fixed effects represent the
#' comparisons of biological interest (often the variables manipulated during
#' experiments), such as treated vs. non-treated, before-treatment vs. after-treatment,
#' or healthy vs. non-healthy.
#'
#' @param random_effect_cols Optional. Unquoted column names representing which columns in
#' `tof_tibble` should be used to model random effects during the differential
#' abundance analysis. Generally speaking, random effects should represent variables
#' that a researcher wants to control/account for, but that are not necessarily
#' of biological interest. Example random effect variables might include batch id,
#' patient id (in a paired design), or patient age.
#'
#' Note that without multiple samples at each level of each of the
#' random effect variables, it can be easy to overfit mixed models. For most high-dimensional cytometry
#' experiments, 2 or fewer (and often 0) random effect variables are appropriate.
#'
#' @param diffcyt_method A string indicating which diffcyt method should be used for the
#' differential abundance analysis. Valid methods include "glmm" (the default),
#' "edgeR", and "voom".
#'
#' @param include_observation_level_random_effects A boolean value indicating
#' if "observation-level random effects" (OLREs) should be included as random effect
#' terms in a "glmm" differential abundance model. For details about what OLREs are, see
#' \href{https://www.nature.com/articles/s42003-019-0415-5}{the diffcyt paper}. Only the
#' "glmm" method can model observation-level random effects, and all other values will ignore
#' this argument (and throw a warning if it is set to TRUE).
#' Defaults to FALSE.
#'
#' @param min_cells An integer value used to filter clusters out of the differential
#' abundance analysis. Clusters are not included in the differential abundance testing
#' if they do not have at least `min_cells` in at least `min_samples` samples.
#' Defaults to 3.
#'
#' @param alpha A numeric value between 0 and 1 indicating which significance
#' level should be applied to multiple-comparison adjusted p-values during the
#' differential abundance analysis. Defaults to 0.05.
#'
#' @param min_samples An integer value used to filter clusters out of the differential
#' abundance analysis. Clusters are not included in the differential abundance testing
#' if they do not have at least `min_cells` in at least `min_samples` samples.
#' Defaults to 5.
#'
#' @param ... Optional additional arguments to pass to the under-the-hood diffcyt
#' function being used to perform the differential abundance analysis. See
#' \code{\link[diffcyt]{testDA_GLMM}}, \code{\link[diffcyt]{testDA_edgeR}}, and
#' \code{\link[diffcyt]{testDA_voom}} for details.
#'
#' @return A nested tibble with two columns: `tested_effect` and `daa_results`.
#'
#' The first column, `tested_effect`
#' is a character vector indicating which term in the differential abundance model
#' was used for significance testing. The values in this row are obtained
#' by pasting together the column names for each fixed effect variable and each
#' of its values. For example, a fixed effect column named `fixed_effect` with
#' levels "a", "b", and "c" have two terms in `tested_effect`: "fixed_effectb" and
#' "fixed_effectc" (note that level "a" of fixed_effect is set as the reference
#' level during dummy coding). These values correspond to the terms in the
#' differential abundance model that represent the difference in cluster abundances
#' between samples with fixed_effect = "b" and fixed_effect = "a" and between
#' samples with fixed_effect = "c" and fixed_effect = "a", respectively. In addition,
#' the first row in `tested_effect` will always represent the "omnibus"
#' test, or the test that there were significant differences between \emph{any} levels of
#' \emph{any} fixed effect variable in the model.
#'
#' The second column, `daa_results` is a list of tibbles in which each entry gives
#' the differential abundance results for each tested_effect. Within each entry
#' of `daa_results`, you will find several columns including the following:
#' * `p_val`, the p-value associated with each
#' tested effect in each input cluster
#' * `p_adj`, the multiple-comparison
#' adjusted p-value (using the \code{\link[stats]{p.adjust}} function)
#' * Other values associated with the underlying method used to perform the
#' differential abundance analysis (such as the log-fold change of cluster
#' abundance between the levels being compared). For details, see
#' \code{\link[edgeR]{glmFit}}, \code{\link[limma]{voom}}, \code{\link[limma]{topTable}},
#' and \code{\link[diffcyt]{testDA_GLMM}}.
#'
#' @family differential abundance analysis functions
#'
#' @export
#'
#' @importFrom rlang arg_match
#' @importFrom tidyselect eval_select
#' @importFrom tidyr unite
#' @importFrom purrr map
#' @importFrom rlang arg_match
#'
#' @examples
#' # For differential discovery examples, please see the package vignettes
#' NULL
#'
tof_analyze_abundance_diffcyt <-
function(
tof_tibble,
sample_col,
cluster_col,
fixed_effect_cols,
random_effect_cols,
diffcyt_method = c("glmm", "edgeR", "voom"),
include_observation_level_random_effects = FALSE,
min_cells = 3,
min_samples = 5,
alpha = 0.05,
...) {
# check to see if the diffcyt package is installed
has_diffcyt <- requireNamespace(package = "diffcyt")
if (!has_diffcyt) {
stop(
"This function requires the {diffcyt} package. Install it with this code:\n
if (!requireNamespace(\"BiocManager\", quietly = TRUE))
install.packages(\"BiocManager\")
BiocManager::install(\"diffcyt\")"
)
}
# check method argument
diffcyt_method <- rlang::arg_match(diffcyt_method)
# edgeR can't model random effects, so we throw an error for the user
# if they are included
if (diffcyt_method == "edgeR" & !missing(random_effect_cols)) {
stop(
"edgeR can't model random effects. Trying using another method or
model everything as a fixed effect."
)
}
# Only the "glmm" method supports observation-level random effects, so
# provide a warning if include_observation_level_random_effects = TRUE
# for any other method.
if (include_observation_level_random_effects == TRUE & diffcyt_method != "glmm") {
message(
"Note: Only the \"glmm\" method can use observation-level random effects.
Setting include_observation_level_random_effects to FALSE.\n"
)
include_observation_level_random_effects <- FALSE
}
# a hack-y approach for dealing with the diffcyt software - we can pick 2 random
# columns corresponding to high-dimensional cytometry measurements to fill the SummarizedExperiment
# that diffcyt requires later, but because in DAA these measurements are not used,
# it doesn't matter that we ignore all the other protein measurements.
#
# This will make the implementation faster for DAA as well because fewer values will
# need to by copied into the SummarizedExperiment data structure.
marker_colnames <-
tof_tibble |>
dplyr::select(dplyr::where(tof_is_numeric)) |>
colnames()
marker_colnames <- marker_colnames[c(1, 2)]
# remove all columns from `tof_tibble` that aren't relevant
tof_tibble <-
tof_tibble |>
dplyr::select(
{{ sample_col }},
dplyr::any_of(marker_colnames),
{{ cluster_col }},
{{ fixed_effect_cols }},
{{ random_effect_cols }}
)
diffcyt_args <-
prepare_diffcyt_args(
tof_tibble = tof_tibble,
sample_col = {{ sample_col }},
cluster_col = {{ cluster_col }},
marker_cols = dplyr::any_of(marker_colnames),
fixed_effect_cols = {{ fixed_effect_cols }},
random_effect_cols = {{ random_effect_cols }},
diffcyt_method = diffcyt_method,
include_observation_level_random_effects =
include_observation_level_random_effects
)
# find counts of each cluster in all samples
cell_counts <- diffcyt::calcCounts(diffcyt_args$data_diff)
# perform difference abundance testing
if (diffcyt_method == "glmm") {
# if glmms are being used,
result_tibble <-
diffcyt_args$contrast_matrix_tibble |>
dplyr::transmute(
tested_effect = .data$contrast_names,
daa_results =
map(
.x = .data$contrast_matrices,
.f = function(x) {
diffcyt::testDA_GLMM(
d_counts = cell_counts,
formula = diffcyt_args$my_formula,
contrast = x,
min_cells = min_cells,
min_samples = min_samples,
...
) |>
diffcyt::topTable(all = TRUE, show_all_cols = TRUE) |>
dplyr::as_tibble() |>
dplyr::arrange(.data$p_adj) |>
dplyr::mutate(
significant = dplyr::if_else(.data$p_adj < alpha, "*", "")
) |>
dplyr::rename("{{cluster_col}}" := "cluster_id")
}
)
)
} else if (diffcyt_method == "voom") {
# if limma/voom is being used,
# We unite all random effect columns and treat them as
# a single block ID. Note this occurs in the help file and that
# it is not recommended to use more than 1 random effect variable with
# the voom method.
if (length(diffcyt_args$random_effect_colnames) != 0) {
# if there are random effects, combine them into a single block_id
block_id <-
diffcyt_args$experiment_info |>
tidyr::unite(
col = "block_id",
dplyr::any_of(diffcyt_args$random_effect_colnames)
) |>
dplyr::pull(.data$block_id) |>
as.factor()
} else {
# otherwise, don't include a block_id
block_id <- NULL
}
result_tibble <-
suppressWarnings(suppressMessages(
diffcyt_args$contrast_matrix_tibble |>
dplyr::transmute(
tested_effect = .data$contrast_names,
daa_results =
purrr::map(
.x = .data$contrast_matrices,
.f = function(x) {
diffcyt::testDA_voom(
d_counts = cell_counts,
design = diffcyt_args$my_design,
contrast = x,
block_id = block_id,
min_cells = min_cells,
min_samples = min_samples,
...
) |>
diffcyt::topTable(all = TRUE, show_all_cols = TRUE) |>
dplyr::as_tibble() |>
dplyr::arrange(.data$p_adj) |>
dplyr::mutate(
significant = dplyr::if_else(.data$p_adj < alpha, "*", "")
) |>
dplyr::select(
"{{cluster_col}}" := "cluster_id",
"p_val",
"p_adj",
"significant",
dplyr::everything()
)
}
)
)
))
} else {
result_tibble <-
diffcyt_args$contrast_matrix_tibble |>
dplyr::transmute(
tested_effect = .data$contrast_names,
daa_results =
purrr::map(
.x = .data$contrast_matrices,
.f = function(x) {
diffcyt::testDA_edgeR(
d_counts = cell_counts,
design = diffcyt_args$my_design,
contrast = x,
min_cells = min_cells,
min_samples = min_samples,
...
) |>
diffcyt::topTable(all = TRUE, show_all_cols = TRUE) |>
dplyr::as_tibble() |>
dplyr::arrange(.data$p_adj) |>
dplyr::mutate(
significant = dplyr::if_else(.data$p_adj < alpha, "*", "")
) |>
dplyr::select(
"{{cluster_col}}" := "cluster_id",
"p_val",
"p_adj",
"significant",
dplyr::everything()
)
}
)
)
}
# remove the omnibus test information (and unnest the results tibble)
# if there are only 2 levels to the fixed effects being tested (because
# this means the omnibus test and the individual effect will be identical)
if (nrow(result_tibble) == 2) {
result_tibble <-
result_tibble |>
dplyr::filter(.data$tested_effect != "omnibus") |>
tidyr::unnest(cols = "daa_results")
}
attr(result_tibble, "daa_method") <- paste0("diffcyt_", diffcyt_method)
return(result_tibble)
}
#' Differential Expression Analysis (DEA) with diffcyt
#'
#' This function performs differential expression analysis on the cell clusters
#' contained within a `tof_tbl` using one of two
#' methods implemented in the \href{https://www.bioconductor.org/packages/release/bioc/html/diffcyt.html}{diffcyt}
#' package for differential discovery analysis in high-dimensional cytometry
#' data.
#'
#' The two methods are based on linear mixed models ("lmm") and
#' \href{https://academic.oup.com/nar/article/43/7/e47/2414268}{limma} ("limma").
#' Both the "lmm" and "limma" methods can model both fixed effects and random
#' effects.
#'
#' @param tof_tibble A `tof_tbl` or a `tibble`.
#'
#' @param sample_col An unquoted column name indicating which column in `tof_tibble`
#' represents the id of the sample from which each cell was collected. `sample_col`
#' should serve as a unique identifier for each sample collected during data acquisition -
#' all cells with the same value for `sample_col` will be treated as a part of the same
#' observational unit.
#'
#' @param cluster_col An unquoted column name indicating which column in `tof_tibble`
#' stores the cluster ids of the cluster to which each cell belongs.
#' Cluster labels can be produced via any method the user chooses - including manual gating,
#' any of the functions in the `tof_cluster_*` function family, or any other method.
#'
#' @param marker_cols Unquoted column names representing which columns in `tof_tibble`
#' (i.e. which high-dimensional cytometry protein measurements) should be tested for differential expression between
#' levels of the `fixed_effect_cols`. Defaults to all numeric (integer or double) columns.
#' Supports tidyselect helpers.
#'
#' @param fixed_effect_cols Unquoted column names representing which columns in
#' `tof_tibble` should be used to model fixed effects during the differential
#' expression analysis. Generally speaking, fixed effects represent the
#' comparisons of biological interest (often the the variables manipulated during
#' experiments), such as treated vs. non-treated, before-treatment vs. after-treatment,
#' or healthy vs. non-healthy.
#'
#' @param random_effect_cols Unquoted column names representing which columns in
#' `tof_tibble` should be used to model random effects during the differential
#' expression analysis. Generally speaking, random effects represent variables
#' that a researcher wants to control/account for, but that are not necessarily
#' of biological interest. Example random effect variables might include batch id,
#' patient id (in a paired design), or patient age.
#'
#' Note that without many samples at each level of each of the
#' random effect variables, it can be easy to overfit mixed models. For most high-dimensional cytometry
#' experiments, 2 or fewer (and often 0) random effect variables are appropriate.
#'
#' @param diffcyt_method A string indicating which diffcyt method should be used for the
#' differential expression analysis. Valid methods include "lmm" (the default)
#' and "limma".
#'
#' @param include_observation_level_random_effects A boolean value indicating
#' if "observation-level random effects" (OLREs) should be included as random effect
#' terms in a "lmm" differential expression model. For details about what OLREs are, see
#' \href{https://www.nature.com/articles/s42003-019-0415-5}{the diffcyt paper}.
#' Defaults to FALSE.
#'
#' @param min_cells An integer value used to filter clusters out of the differential
#' expression analysis. Clusters are not included in the differential expression testing
#' if they do not have at least `min_cells` in at least `min_samples` samples.
#' Defaults to 3.
#'
#' @param min_samples An integer value used to filter clusters out of the differential
#' expression analysis. Clusters are not included in the differential expression testing
#' if they do not have at least `min_cells` in at least `min_samples` samples.
#' Defaults to 5.
#'
#' @param alpha A numeric value between 0 and 1 indicating which significance
#' level should be applied to multiple-comparison adjusted p-values during the
#' differential abundance analysis. Defaults to 0.05.
#'
#' @param ... Optional additional arguments to pass to the under-the-hood diffcyt
#' function being used to perform the differential expression analysis. See
#' \code{\link[diffcyt]{testDS_LMM}} and \code{\link[diffcyt]{testDS_limma}}
#' for details.
#'
#' @return A nested tibble with two columns: `tested_effect` and `dea_results`.
#'
#' The first column, `tested_effect`
#' is a character vector indicating which term in the differential expression model
#' was used for significance testing. The values in this row are obtained
#' by pasting together the column names for each fixed effect variable and each
#' of its values. For example, a fixed effect column named fixed_effect with
#' levels "a", "b", and "c" have two terms in `tested_effect`: "fixed_effectb" and
#' "fixed_effectc" (note that level "a" of fixed_effect is set as the reference
#' level during dummy coding). These values correspond to the terms in the
#' differential expression model that represent the difference in cluster median
#' expression values of each marker between samples with fixed_effect = "b" and
#' fixed_effect = "a" and between samples with fixed_effect = "c" and
#' fixed_effect = "a", respectively. In addition,
#' note that the first row in `tested_effect` will always represent the "omnibus"
#' test, or the test that there are significant differences between \emph{any} levels of
#' \emph{any} fixed effect variable in the model.
#'
#' The second column, `dea_results` is a list of tibbles in which each entry gives
#' the differential expression results for each tested_effect. Within each entry
#' of `dea_results`, you will find `p_val`, the p-value associated with each
#' tested effect in each input cluster/marker pair; `p_adj`, the multiple-comparison
#' adjusted p-value (using the \code{\link[stats]{p.adjust}} function), and
#' other values associated with the underlying method used to perform the
#' differential expression analysis (such as the log-fold change of clusters' median
#' marker expression values between the conditions being compared). Each tibble in `dea_results`
#' will also have two columns representing the cluster and marker corresponding to the
#' p-value in each row.
#'
#' @family differential expression analysis functions
#'
#' @export
#'
#' @importFrom purrr pluck
#' @importFrom tidyr unite
#'
#' @examples
#' # For differential discovery examples, please see the package vignettes
#' NULL
#'
tof_analyze_expression_diffcyt <-
function(
tof_tibble,
sample_col,
cluster_col,
marker_cols = where(tof_is_numeric),
fixed_effect_cols,
random_effect_cols,
diffcyt_method = c("lmm", "limma"),
include_observation_level_random_effects = FALSE,
min_cells = 3,
min_samples = 5,
alpha = 0.05,
...) {
# check to see if the diffcyt package is installed
has_diffcyt <- requireNamespace(package = "diffcyt")
if (!has_diffcyt) {
stop(
"This function requires the {diffcyt} package. Install it with this code:\n
if (!requireNamespace(\"BiocManager\", quietly = TRUE)){
install.packages(\"BiocManager\")
BiocManager::install(\"diffcyt\")
}"
)
}
# check diffcyt_method argument
diffcyt_method <- match.arg(diffcyt_method, choices = c("lmm", "limma"))
# Only the "lmm" method supports observation-level random effects, so
# provide a warning if include_observation_level_random_effects = TRUE
# for any other method.
if (include_observation_level_random_effects == TRUE & diffcyt_method != "lmm") {
message(
"Note: Only the \"lmm\" method can use observation-level random effects.
Setting include_observation_level_random_effects to FALSE.\n"
)
}
# remove all columns from `tof_tibble` that aren't relevant
tof_tibble <-
tof_tibble |>
dplyr::select(
{{ sample_col }},
{{ cluster_col }},
{{ marker_cols }},
{{ fixed_effect_cols }},
{{ random_effect_cols }}
)
diffcyt_args <-
prepare_diffcyt_args(
tof_tibble = tof_tibble,
sample_col = {{ sample_col }},
cluster_col = {{ cluster_col }},
marker_cols = {{ marker_cols }},
fixed_effect_cols = {{ fixed_effect_cols }},
random_effect_cols = {{ random_effect_cols }},
diffcyt_method = diffcyt_method,
include_observation_level_random_effects =
include_observation_level_random_effects
)
# find cluster counts and cluster medians
cell_counts <- diffcyt::calcCounts(diffcyt_args$data_diff)
cell_medians <- diffcyt::calcMedians(diffcyt_args$data_diff)
# Perform the differential expression analysis
my_contrast <-
diffcyt_args$contrast_matrix_tibble |>
dplyr::pull(.data$contrast_matrices) |>
purrr::pluck(1)
if (diffcyt_method == "lmm") {
# if lmm's are being used,
result_tibble <-
suppressWarnings(suppressMessages(
diffcyt_args$contrast_matrix_tibble |>
dplyr::transmute(
tested_effect = .data$contrast_names,
dea_results =
purrr::map(
.x = .data$contrast_matrices,
.f = function(x) {
diffcyt::testDS_LMM(
d_counts = cell_counts,
d_medians = cell_medians,
formula = diffcyt_args$my_formula,
contrast = x,
markers_to_test = rep(TRUE, nrow(diffcyt_args$marker_info)),
min_cells = min_cells,
min_samples = min_samples,
...
) |>
diffcyt::topTable(all = TRUE, show_all_cols = TRUE) |>
dplyr::as_tibble() |>
dplyr::mutate(
significant = dplyr::if_else(.data$p_adj < alpha, "*", ""),
cluster_id = as.character(.data$cluster_id),
marker_id = as.character(.data$marker_id)
) |>
dplyr::rename(
marker = .data$marker_id,
"{{cluster_col}}" := "cluster_id"
) |>
dplyr::select(
{{ cluster_col }},
"marker",
"p_val",
"p_adj",
"significant",
dplyr::everything()
)
}
)
)
))
} else if (diffcyt_method == "limma") {
# if limma is being used,
if (length(diffcyt_args$random_effect_colnames) != 0) {
# if there are random effects, combine them into a single block_id
block_id <-
diffcyt_args$experiment_info |>
tidyr::unite(
col = "block_id",
dplyr::any_of(diffcyt_args$random_effect_colnames)
) |>
dplyr::pull(.data$block_id) |>
as.factor()
} else {
# otherwise, don't include a block_id
block_id <- NULL
}
result_tibble <-
suppressWarnings(suppressMessages(
diffcyt_args$contrast_matrix_tibble |>
dplyr::transmute(
tested_effect = .data$contrast_names,
dea_results =
purrr::map(
.x = .data$contrast_matrices,
.f = function(x) {
diffcyt::testDS_limma(
d_counts = cell_counts,
d_medians = cell_medians,
design = diffcyt_args$my_design,
contrast = x,
block_id = block_id,
min_cells = min_cells,
min_samples = min_samples,
markers_to_test = rep(TRUE, nrow(diffcyt_args$marker_info)),
...
) |>
diffcyt::topTable(all = TRUE, show_all_cols = TRUE) |>
dplyr::as_tibble() |>
select(-.data$ID) |>
dplyr::mutate(
significant = dplyr::if_else(.data$p_adj < alpha, "*", ""),
cluster_id = as.character(.data$cluster_id),
marker_id = as.character(.data$marker_id)
) |>
dplyr::rename(
marker = .data$marker_id,
"{{cluster_col}}" := "cluster_id"
) |>
dplyr::select(
{{ cluster_col }},
"marker",
"p_val",
"p_adj",
"significant",
dplyr::everything()
)
}
)
)
))
}
# remove the omnibus test information (and unnest the results tibble)
# if there are only 2 levels to the fixed effects being tested (because
# this means the omnibus test and the individual effect will be identical)
if (nrow(result_tibble) == 2) {
result_tibble <-
result_tibble |>
dplyr::filter(.data$tested_effect != "omnibus") |>
tidyr::unnest(cols = "dea_results")
}
attr(result_tibble, "dea_method") <- paste0("diffcyt_", diffcyt_method)
return(result_tibble)
}
# GLMs and GLMMs ---------------------------------------------------------------
#' Differential Abundance Analysis (DAA) with generalized linear mixed-models (GLMMs)
#'
#' This function performs differential abundance analysis on the cell clusters
#' contained within a `tof_tbl` using generalized linear mixed-models. Users
#' specify which columns represent sample, cluster, fixed effect, and random effect
#' information, and a (mixed) binomial regression model is fit using either
#' \code{\link[lme4]{glmer}} or \code{\link[stats]{glm}}.
#'
#' @param tof_tibble A `tof_tbl` or a `tibble`.
#'
#' @param sample_col An unquoted column name indicating which column in `tof_tibble`
#' represents the id of the sample from which each cell was collected. `sample_col`
#' should serve as a unique identifier for each sample collected during data acquisition -
#' all cells with the same value for `sample_col` will be treated as a part of the same
#' observational unit.
#'
#' @param cluster_col An unquoted column name indicating which column in `tof_tibble`
#' stores the cluster ids of the cluster to which each cell belongs.
#' Cluster labels can be produced via any method the user chooses - including manual gating,
#' any of the functions in the `tof_cluster_*` function family, or any other method.
#'
#' @param fixed_effect_cols Unquoted column names representing which columns in
#' `tof_tibble` should be used to model fixed effects during the differential
#' abundance analysis. Supports tidyselect helpers.
#'
#' Generally speaking, fixed effects should represent the
#' comparisons of biological interest (often the the variables manipulated during
#' experiments), such as treated vs. non-treated, before-treatment vs. after-treatment,
#' or healthy vs. non-healthy.
#'
#' @param random_effect_cols Unquoted column names representing which columns in
#' `tof_tibble` should be used to model random effects during the differential
#' abundance analysis. Supports tidyselection.
#'
#' Generally speaking, random effects should represent variables
#' that a researcher wants to control/account for, but that are not necessarily
#' of biological interest. Example random effect variables might include batch id,
#' patient id (in a paired design), or patient age.
#'
#' Note that without many samples at each level of each of the
#' random effect variables, it can be easy to overfit mixed models. For most high-dimensional cytometry
#' experiments, 2 or fewer (and often 0) random effect variables are appropriate.
#'
#' @param min_cells An integer value used to filter clusters out of the differential
#' abundance analysis. Clusters are not included in the differential abundance testing
#' if they do not have at least `min_cells` in at least `min_samples` samples.
#' Defaults to 3.
#'
#' @param min_samples An integer value used to filter clusters out of the differential
#' abundance analysis. Clusters are not included in the differential abundance testing
#' if they do not have at least `min_cells` in at least `min_samples` samples.
#' Defaults to 5.
#'
#' @param alpha A numeric value between 0 and 1 indicating which significance
#' level should be applied to multiple-comparison adjusted p-values during the
#' differential abundance analysis. Defaults to 0.05.
#'
#' @return A nested tibble with two columns: `tested_effect` and `daa_results`.
#'
#' The first column, `tested_effect`,
#' is a character vector indicating which term in the differential abundance model
#' was used for significance testing. The values in this row are obtained
#' by pasting together the column names for each fixed effect variable and each
#' of its values. For example, a fixed effect column named fixed_effect with
#' levels "a", "b", and "c" have two terms in `tested_effect`: "fixed_effectb" and
#' "fixed_effectc" (note that level "a" of fixed_effect is set as the reference
#' level during dummy coding). These values correspond to the terms in the
#' differential abundance model that represent the difference in cluster abundances
#' between samples with fixed_effect = "b" and fixed_effect = "a" and between
#' samples with fixed_effect = "c" and fixed_effect = "a", respectively. In addition,
#' note that the first row in `tested_effect` will always represent the "omnibus"
#' test, or the test that there were significant differences between any levels of
#' any fixed effect variable in the model.
#'
#' The second column, `daa_results`, is a list of tibbles in which each entry gives
#' the differential abundance results for each tested_effect. Within each entry
#' of `daa_results`, you will find `p_value`, the p-value associated with each
#' tested effect in each input cluster; `p_adj`, the multiple-comparison
#' adjusted p-value (using the \code{\link[stats]{p.adjust}} function), and
#' other values associated with the underlying method used to perform the
#' differential abundance analysis (such as the log-fold change of cluster
#' abundance between the levels being compared).
#'
#' @family differential abundance analysis functions
#'
#' @export
#'
#' @importFrom rlang enquo
#' @importFrom tidyselect eval_select
#' @importFrom tidyr pivot_longer
#' @importFrom tidyr nest
#' @importFrom stringr str_c
#' @importFrom stats as.formula
#' @importFrom purrr map
#'
#' @examples
#' # For differential discovery examples, please see the package vignettes
#' NULL
#'
tof_analyze_abundance_glmm <-
function(
tof_tibble,
sample_col,
cluster_col,
fixed_effect_cols,
random_effect_cols,
min_cells = 3,
min_samples = 5,
alpha = 0.05) {
# extract sample column as a character vector
# will return an empty character vector if the argument is missing
sample_colname <-
tidyselect::eval_select(
expr = rlang::enquo(sample_col),
data = tof_tibble
) |>
names()
# extract fixed effect columns as a character vector
# will return an empty character vector if the argument is missing
fixed_effect_colnames <-
tidyselect::eval_select(
expr = rlang::enquo(fixed_effect_cols),
data = tof_tibble
) |>
names()
if (length(fixed_effect_colnames) == 0) {
stop("Fixed effects must be specified. Did you forget to set the `fixed_effect_cols` argument?")
}
# extract random effect columns as a character vector
# will return an empty character vector if the argument is missing
random_effect_colnames <-
tidyselect::eval_select(
expr = rlang::enquo(random_effect_cols),
data = tof_tibble
) |>
names()
# count cells in all samples
my_sep <- "_______"
cell_counts <-
tof_tibble |>
tidyr::unite(
col = "metadata",
c({{ sample_col }}, dplyr::any_of(c(fixed_effect_colnames, random_effect_colnames))),
sep = my_sep
) |>
dplyr::mutate(
dplyr::across(
c("metadata", {{ cluster_col }}),
.f = as.factor
),
) |>
dplyr::count(.data$metadata, {{ cluster_col }}, name = "num_cells", .drop = FALSE) |>
tidyr::separate(
col = "metadata",
into = c(sample_colname, fixed_effect_colnames, random_effect_colnames),
sep = my_sep
) |>
dplyr::mutate("{{cluster_col}}" := as.character({{ cluster_col }})) |>
dplyr::group_by({{ sample_col }}) |>
dplyr::mutate(
total_cells = sum(.data$num_cells),
prop = .data$num_cells / .data$total_cells
) |>
dplyr::ungroup()
# find the clusters that don't have over the threshold of minimum cells
# in over the threshold of minimum samples
clusters_to_remove <-
cell_counts |>
dplyr::count(
{{ sample_col }},
{{ cluster_col }},
wt = .data$num_cells,
.drop = FALSE
) |>
dplyr::mutate(has_over_min_cells = .data$n > min_cells) |>
dplyr::count({{ cluster_col }}, .data$has_over_min_cells) |>
dplyr::filter(.data$has_over_min_cells) |>
dplyr::filter(.data$n < min_samples) |>
dplyr::pull({{ cluster_col }})
cell_counts <-
cell_counts |>
dplyr::filter(!({{ cluster_col }} %in% clusters_to_remove))
# nest the count data so we can fit one model per cluster
fit_data <-
cell_counts |>
dplyr::group_by({{ cluster_col }}) |>
tidyr::nest() |>
dplyr::ungroup()
# specify if there are random effects
if (length(random_effect_colnames) == 0) {
has_random_effects <- FALSE
} else {
has_random_effects <- TRUE
}
# construct formula for each model
if (has_random_effects) {
formula_string <-
stringr::str_c(
"prop ~ ",
stringr::str_c(fixed_effect_colnames, sep = "+", collapse = " + "),
"+",
stringr::str_c(paste0("(1 | ", random_effect_colnames, ")"), sep = "+")
)
} else {
formula_string <-
stringr::str_c(
"prop ~ ",
stringr::str_c(fixed_effect_colnames, sep = "+", collapse = " + "),
sep = ""
)
}
formula <- stats::as.formula(formula_string)
# fit one model per cluster
fit_data <-
suppressMessages(suppressWarnings(
fit_data |>
dplyr::mutate(
results =
purrr::map(
.x = data,
.f = fit_da_model,
formula = formula,
has_random_effects = has_random_effects
),
results = purrr::map(.x = .data$results, .f = tidy_lmer_test_glmm)
)
))
fit_data <-
fit_data |>
dplyr::select(-"data") |>
tidyr::unnest(cols = "results") |>
dplyr::filter(.data$term != "(Intercept)", !is.na(.data$p.value)) |>
dplyr::mutate(p_adj = stats::p.adjust(.data$p.value, method = "fdr")) |>
dplyr::arrange(.data$p_adj) |>
dplyr::mutate(
significant = dplyr::if_else(.data$p_adj < alpha, "*", ""),
mean_fc = exp(.data$estimate)
) |>
dplyr::rename(
tested_effect = "term",
p_val = "p.value",
f_statistic = "statistic"
)
# if (has_random_effects) {
# fit_data <-
# fit_data |>
# dplyr::select(-.data$group, -.data$effect)
# }
fit_data <-
fit_data |>
dplyr::rename_with(stringr::str_replace_all, pattern = "(?<=.)\\.", replacement = "_") |>
dplyr::select(
{{ cluster_col }},
"p_val",
"p_adj",
"significant",
tidyselect::everything()
) |>
tidyr::nest(daa_results = c(-"tested_effect"))
# if result tibble only has 1 row (only 2 levels of fixed_effect_cols), \
# unnest it (which is more intuitive)
if (nrow(fit_data) == 1) {
fit_data <-
tidyr::unnest(fit_data, cols = "daa_results")
}
attr(fit_data, which = "daa_method") <- "glmm"
return(fit_data)
}
#' Differential Expression Analysis (DEA) with linear mixed-models (LMMs)
#'
#' This function performs differential expression analysis on the cell clusters
#' contained within a `tof_tbl` using linear mixed-models. Users
#' specify which columns represent sample, cluster, marker, fixed effect, and random effect
#' information, and a (mixed) linear regression model is fit using either
#' \code{\link[lmerTest]{lmer}} or \code{\link[stats]{glm}}.
#'
#' Specifically, one linear model is fit for each cluster/marker pair. For each cluster/marker
#' pair, a user-supplied measurement of central tendency (`central_tendency_function`), such
#' as mean or median, is calculated across all cells in the cluster on a sample-by-sample
#' basis. Then, this central tendency value is used as the dependent variable in a
#' linear model with `fixed_effect_cols` as fixed effects predictors and `random_effect_cols`
#' as random effects predictors. Once all models (one per each cluster/marker pair) are fit,
#' p-values for each coefficient in each model are multiple-comparisons adjusted using the
#' \code{\link[stats]{p.adjust}} function.
#'
#' @param tof_tibble A `tof_tbl` or a `tibble`.
#'
#' @param sample_col An unquoted column name indicating which column in `tof_tibble`
#' represents the id of the sample from which each cell was collected. `sample_col`
#' should serve as a unique identifier for each sample collected during data acquisition -
#' all cells with the same value for `sample_col` will be treated as a part of the same
#' observational unit.
#'
#' @param cluster_col An unquoted column name indicating which column in `tof_tibble`
#' stores the cluster ids of the cluster to which each cell belongs.
#' Cluster labels can be produced via any method the user chooses - including manual gating,
#' any of the functions in the `tof_cluster_*` function family, or any other method.
#'
#' @param marker_cols Unquoted column names representing which columns in `tof_tibble`
#' (i.e. which high-dimensional cytometry protein measurements) should be included in the differential
#' discovery analysis. Defaults to all numeric (integer or double) columns.
#' Supports tidyselection.
#'
#' @param fixed_effect_cols Unquoted column names representing which columns in
#' `tof_tibble` should be used to model fixed effects during the differential
#' expression analysis. Supports tidyselection.