-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.R
3524 lines (3207 loc) · 124 KB
/
utils.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
sink_all <- function(expr, output_file) {
# Open the output file for writing and messages
out_file <- file(output_file, open = "wt")
# Close the sinks and the file connection
on.exit({
sink(type = "message")
sink()
close(out_file)
cat("Sink closed. Output redirected to ", output_file, "\n")
})
sink(out_file, type = "message")
sink(out_file, type = "output", append = TRUE)
# Capture warnings and errors using tryCatch
withCallingHandlers({
eval(expr, envir = parent.frame())
}, warning = function(w) {
cat("\nWarning: ", w$message, "\n", file = out_file, append = TRUE)
}, error = function(e) {
cat("\nError: ", conditionMessage(e), "\n", file = out_file, append = TRUE)
})
}
Mode <- function(x, na.rm = FALSE) {
if (na.rm) {
x <- x[!is.na(x)]
}
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
filter_cell_types <- function(data, grouping_vars, min_n, min_pct, covs_n,
donor_col = "donor", cell_type_col = "cell_type",
num_cells_col = "num_cells") {
#' Filter cell types based on specified criteria
#'
#' This function filters cell types based on the specified criteria, including
#' the number of donors (\code{min_n}), the percentage of non-zero
#' \code{num_cells}, and the number of grouping variables (\code{covs_n}).
#'
#' @param data A data frame containing the relevant columns.
#' @param grouping_vars A character vector specifying the grouping variable(s).
#' @param min_n The minimum number of donors for a cell type to be considered.
#' @param min_pct The minimum percentage of non-zero \code{num_cells} for a
#' cell type to be considered.
#' @param covs_n The minimum number of grouping variables to be considered.
#' @param donor_col The name of the column containing donor information.
#' @param cell_type_col The name of the column containing cell type information.
#' @param num_cells_col The name of the column containing the number of cells information.
#'
#' @return A character vector containing the filtered cell types.
#'
#' @details This function filters cell types based on the specified criteria. It checks for
#' the minimum number of donors (\code{min_n}), the minimum percentage of non-zero
#' \code{num_cells} (\code{min_pct}), and the minimum number of grouping variables (\code{covs_n}).
#' The resulting character vector contains the cell types that meet the specified criteria.
#'
#' @examples
#' \dontrun{
#' filtered_types <- filter_cell_types(your_data, c("grouping_var1", "grouping_var2"), 5, 0.1, 3)
#' }
#'
#' @seealso \code{\link{dplyr::group_by}}, \code{\link{dplyr::summarize}}, \code{\link{dplyr::filter}},
#' \code{\link{tidyr::drop_na}}, \code{\link{tidyr::pull}}
#'
#' @importFrom dplyr n_distinct group_by summarize filter pull
#' @importFrom tidyr drop_na
#'
#' @export
# Safety checks
if (!is.data.frame(data)) {
stop("Input 'data' must be a data frame.")
}
if (!is.character(grouping_vars) || length(grouping_vars) == 0) {
stop("Input 'grouping_vars' must be a non-empty character vector.")
}
if (!is.character(donor_col) || !is.character(cell_type_col) || !is.character(num_cells_col)) {
stop("Columns 'donor_col', 'cell_type_col', and 'num_cells_col' must be character strings.")
}
if (!is.numeric(min_n) || !is.numeric(min_pct) || !is.numeric(covs_n)) {
stop("Inputs 'min_n', 'min_pct', and 'covs_n' must be numeric.")
}
# Remove continuous grouping variables
if (any(purrr::map_lgl(data[,grouping_vars], is.numeric))) {
grouping_vars <- grouping_vars[!purrr::map_lgl(data[,grouping_vars],
is.numeric)]
}
# Get unique cell types
cell_types <- unique(data[[cell_type_col]])
cell_types <- structure(cell_types, names = cell_types)
# Filter
cell_types_filtered <- data %>%
tidyr::drop_na(!!sym(cell_type_col)) %>%
{
# Group by multiple categorical grouping variables
if (length(grouping_vars) > 1) {
dplyr::group_by(., !!sym(cell_type_col), !!!syms(grouping_vars))
} else if (length(grouping_vars) == 1) {
# Group by a single categorical grouping variable
dplyr::group_by(., !!sym(cell_type_col), !!sym(grouping_vars))
} else {
# Group by cell type only
dplyr::group_by(., !!sym(cell_type_col))
}
} %>%
dplyr::summarize(
n_donor = dplyr::n_distinct(!!sym(donor_col)),
absent = mean(!!sym(num_cells_col) != 0) <= min_pct
) %>%
dplyr::filter(n_donor >= min_n, absent == FALSE) %>%
dplyr::group_by(!!sym(cell_type_col)) %>%
dplyr::summarize(., n_donor = sum(n_donor)) %>%
dplyr::filter(n_donor >= covs_n) %>%
dplyr::pull(!!sym(cell_type_col))
# Return filtered cell types
cell_types[cell_types %in% cell_types_filtered]
}
pycat_to_rfactor <- function(x) {
#' Convert Python-style categorical data to R factor
#'
#' This function converts Python-style categorical data with a combination
#' of `categories` and `codes` into an R factor. \href{https://github.com/scverse/anndata/blob/a96205c58738b7054d7ed663707c2fec6b52e31d/docs/fileformat-prose.rst#id11}{Source}.
#'
#' @param x A list containing the categorical data. Expected to have elements
#' `categories` and `codes` (numeric indices referring to the categories).
#' @return An R factor corresponding to the Python-style categorical data.
#' @examples
#' # Example input
#' pycat <- list(categories = c("A", "B", "C"), codes = c(0, 1, 2, 0, 1))
#' pycat_to_rfactor(pycat)
#' # [1] A B C A B
#' # Levels: A B C
stopifnot(is.list(x))
if (sum(names(x) %in% c("mask", "values")) == 2) {
# Category bool to integer vector
y <- x$values[ifelse(x$mask == T, NA, T)]
} else if (sum(names(x$categories) %in% c("mask", "values")) == 2) {
# Category str of int/float to numeric vector
## Mask == F if not NA
x$categories <- as.character(x$categories$values[x$categories$mask == F])
x$codes[x$codes == -1] <- NA
y <- factor(x$categories[x$codes + 1])
} else if (sum(names(x) %in% c("categories", "codes")) == 2) {
# Category str to character factor
x$codes[x$codes == -1] <- NA
y <- factor(x$categories[x$codes + 1])
} else {
stop("Could not map python category to R vector")
}
return(y)
}
get_h5ad_meta <- function(h5ad, FactorsAsStrings = T) {
#' Extract Metadata from h5ad File
#'
#' This function reads an h5ad file and extracts cell metadata, handling
#' both SEA-AD and Scanpy formats. Metadata is returned as a `data.frame`,
#' with cell IDs as row names.
#'
#' @param h5ad A character string. The file path to the h5ad file.
#' @return A `data.frame` containing the cell metadata with cell IDs as
#' row names. Columns correspond to metadata attributes from the h5ad file.
#' @details
#' The function supports both SEA-AD and Scanpy formats:
#' - For SEA-AD, categorical variables are converted to factors using the
#' `__categories` attribute.
#' - For Scanpy, Python-style categorical data (`categories`, `codes`) are
#' converted to R factors.
#'
#' The function validates the file format, ensures consistent cell IDs
#' and metadata columns, and replaces illegal column names.
#'
#' @examples
#' # Example usage:
#' metadata <- get_h5ad_meta("path/to/file.h5ad")
#' head(metadata)
#'
#' @seealso [pycat_to_rfactor()] for converting categorical data.
#' @export
suppressPackageStartupMessages({
library(tools)
library(rhdf5)
library(purrr)
})
stopifnot(file.exists(h5ad))
stopifnot(tools::file_ext(h5ad) == "h5ad")
# Import obs and extract cell IDs
obs <- tryCatch({
rhdf5::h5read(h5ad, "obs", read.attributes = T)
}, error = function(e) {
stop("Error reading 'obs' from h5ad file: ", conditionMessage(e))
})
rhdf5::h5closeAll()
# Extract cell IDs
if (!"_index" %in% names(attributes(obs))) {
stop("Missing '_index' attribute in 'obs'.")
}
obs_i <- as.character(obs[[attributes(obs)[["_index"]]]])
# Handle SEA-AD's format
if ("__categories" %in% names(obs)) {
cats <- names(obs)[names(obs) %in% names(obs[["__categories"]])]
cats <- structure(cats, names = cats)
cats <- purrr::map(cats, ~ factor(obs[[.x]],
labels = obs[["__categories"]][[.x]]))
num <- names(obs)[!names(obs) %in% names(obs[["__categories"]]) &
names(obs) != "__categories"]
d <- c(cats, obs[num])
} else {
# Handle Scanpy's format
valid_names <- c("categories", "codes", "mask", "values")
for (i in which(purrr::map_int(obs, purrr::vec_depth) == 3)) {
if (!sum(names(obs[[i]]) %in% valid_names) == 2) {
.y <- paste0(names(obs[i]), "/", names(obs[[i]]))
obs[i] <- unlist(obs[i], F, F)
names(obs)[i] <- .y
warning("Illegal column names were replaced")
}
}
# Transform categories (length(.x) == 2) to factors
d <- purrr::modify_if(obs, .p = ~ length(.x) == 2,
.f = ~ pycat_to_rfactor(.x))
}
# Validate and enframe metadata
if (!purrr::every(d, ~ length(.x) == length(obs_i))) {
stop("Mismatch between cell metadata and cell IDs.")
}
if (!"column-order" %in% names(attributes(obs))) {
stop("Missing 'column-order' attribute in 'obs'.")
}
obs <- tryCatch({
data.frame(d, check.names = F, stringsAsFactors = F)[
, attributes(obs)[["column-order"]]]
}, error = function(e) {
stop("Error constructing data frame from obs: ", conditionMessage(e))
})
rownames(obs) <- obs_i
# Convert factors to string
if (FactorsAsStrings) {
i <- sapply(obs, is.factor)
obs[i] <- lapply(obs[i], as.character)
}
return(obs)
}
get_h5ad_expr <- function(h5ad, transpose = T, class = "H5SparseMatrix") {
#' Extract Expression Matrix from h5ad File
#'
#' This function extracts the expression matrix from an h5ad file. It ensures
#' the row and column indices (e.g., gene names and cell IDs) are correctly
#' assigned, handling cases where the gene names may be stored as indices
#' or categorical variables.
#'
#' @param h5ad A character string. The file path to the h5ad file.
#' @param transpose logical. Whether to transpose the cell-by-gene matrix to
#' return gene-by-cell instead.
#' @param class character. Either "sparseMatrix" or "H5SparseMatrix". The
#' latter is useful for large matrices that need to be stored using bit64
#' (note, spam does not accept dimnames).
#' @return A `Matrix` object containing the expression data, with genes as rows
#' and cells as columns. Row names represent gene names, and column names
#' represent cell IDs.
#' @details
#' The function ensures robust handling of different storage formats:
#' - Gene names (`var`) can be stored as `_index`, `feature_name`, or
#' `feature_names`.
#' - Handles categorical storage formats where gene names are represented as
#' codes and categories.
#'
#' It uses the `rhdf5` package to efficiently read the h5ad file and close all
#' connections to avoid warnings or resource leaks.
#'
#' @examples
#' # Extract the expression matrix from an h5ad file
#' expr <- get_h5ad_expr("path/to/file.h5ad")
#' dim(expr) # Check dimensions of the expression matrix
#'
#' @seealso [get_h5ad_meta()] for extracting metadata from h5ad files.
#' @export
suppressPackageStartupMessages({
library(tools)
library(rhdf5)
library(purrr)
})
stopifnot(file.exists(h5ad))
stopifnot(tools::file_ext(h5ad) == "h5ad")
# Import cell names
obs_attr <- rhdf5::h5readAttributes(h5ad, "obs")
obs_i <- tryCatch({
if (!is.null(obs_attr[["_index"]])) {
rhdf5::h5read(h5ad, paste0("obs/", obs_attr[["_index"]]))
} else {
stop("Critical error: Missing '_index' attribute for obs.")
}
}, error = function(e) {
stop("Unable to load obs names: ", conditionMessage(e))
NULL
})
# Import gene names
var_attr <- rhdf5::h5readAttributes(h5ad, "var")
var_i <- tryCatch({
if (!is.null(var_attr[["_index"]])) {
var_i_data <- rhdf5::h5read(h5ad, paste0("var/", var_attr[["_index"]]))
# Handle if the index is categorical
if (is.list(var_i_data) &&
all(c("codes", "categories") %in% names(var_i_data))) {
var_i_data$categories[var_i_data$codes + 1]
} else {
var_i_data
}
} else {
stop("Critical error: Missing '_index' attribute for obs.")
}
}, error = function(e) {
stop("Unable to load var names: ", conditionMessage(e))
NULL
})
rhdf5::h5closeAll()
# Import matrix
if (class == "sparseMatrix") {
suppressPackageStartupMessages(library(Matrix))
X <- rhdf5::h5read(h5ad, "X", read.attributes = T,
bit64conversion = "bit64")
rhdf5::h5closeAll()
if (purrr::every(X, ~ class(.x) == "array")) {
X <- purrr::modify_at(X, 1:3, as.numeric)
}
# Read in matrix
if (attributes(X)[["encoding-type"]] == "csr_matrix") {
X <- Matrix::sparseMatrix(
j = X$indices,
p = X$indptr,
x = X$data,
dims = attributes(X)$shape,
dimnames = list(obs_i, var_i),
index1 = F,
repr = "R"
)
} else if (attributes(X)[["encoding-type"]] == "csc_matrix") {
X <- Matrix::sparseMatrix(
i = X$indices,
p = X$indptr,
x = X$data,
dims = attributes(X)$shape,
dimnames = list(obs_i, var_i),
index1 = F,
repr = "C"
)
} else if (attributes(X)[["encoding-type"]] == "coo_matrix") {
X <- Matrix::sparseMatrix(
i = X$row,
j = X$col,
x = X$data,
dims = attributes(X)$shape,
dimnames = list(obs_i, var_i),
index1 = F,
repr = "T"
)
}
if (transpose) X <- Matrix::t(X)
} else if (class == "H5SparseMatrix") {
# Read delayed saprse matrix
X <- HDF5Array::H5SparseMatrix(h5ad, "X")
X <- provideDimnames(X, base = list(var_i, obs_i))
if (!transpose) X <- Matrix::t(X)
}
return(X)
}
get_h5ad <- function(h5ad, transpose = T, class = "H5SparseMatrix",
FactorsAsStrings = T) {
# Extracts sparse matrix and cell metadata from h5ad.
# h5ad character. Path to h5ad file.
# transpose logical. Whether to transpose the cellsxgenes matrix to return genesxcells.
# class character. Either "sparseMatrix" or "spam". The latter is useful for large matrices that need to be stored using bit64.
meta <- get_h5ad_meta(h5ad, FactorsAsStrings = FactorsAsStrings)
expr <- get_h5ad_expr(h5ad, class = class)
return(list(expr = expr, meta = meta))
}
merge.sparse <- function(...) {
# Merge sparse matrices by adding values of unique combinations of indeces
# ... Sparse matrix.
# Example:
# B <- sparseMatrix(c(1,3,5), c(3,6,3), x = c(1,4,1))
# rownames(B) <- letters[1:nrow(B)]
# colnames(B) <- LETTERS[1:ncol(B)]
# merge.sparse(B, B[1:3, 1:3])
# Reduce(merge.sparse, list(B, B[1:3, 1:3], B[1:5, 1:5], B[3:5, 2:4]))
#
# https://www.appsloveworld.com/r/100/71/r-binding-sparse-matrices-of-different-sizes-on-rows
suppressPackageStartupMessages(library(Matrix))
cnnew <- character()
rnnew <- character()
x <- vector()
i <- numeric()
j <- numeric()
for (M in list(...)) {
cnold <- colnames(M)
rnold <- rownames(M)
stopifnot(!is.null(cnold) & !is.null(rnold))
cnnew <- union(cnnew, cnold)
rnnew <- union(rnnew, rnold)
cindnew <- match(cnold, cnnew)
rindnew <- match(rnold, rnnew)
ind <- Matrix::summary(M)
i <- c(i, rindnew[ind[, 1]])
j <- c(j, cindnew[ind[, 2]])
x <- c(x, M@x)
}
return(Matrix::sparseMatrix(
i = i,
j = j,
x = x,
dims = c(length(rnnew), length(cnnew)),
dimnames = list(rnnew, cnnew)
))
}
h5ad_de <- function(fs = fs, replicate_col = "projid", replicate_col_ids = NULL,
cell_type_col = "state", label_col = "pmAD",
de_family = "pseudobulk", de_method = "limma",
de_type = "voom", model = NULL, groups_label = NULL,
verbose = F) {
# Runs limma voom on pseudobulked count matrices from h5ad files
# fs character. h5ad filenames. If named, the resulting dataframe will use those to refer to the cell type in question.
# replicate_col character. See Libra.
# replicate_col_ids character. replicate_col values to be included in the DE analysis. Used for subsetting to specific individuals.
# label_col character. See Libra.
# de_family character. See Libra.
# de_method character. See Libra.
# de_type character. See Libra.
# model character. See Libra.
# groups_label character. h5ad filename label shared by multiple h5ads in fs.
# verbose character. See Libra.
#
# Examples
# # Get existing files
# fs <- list.files("data/integrated/p400", "*.h5ad", full.names = T)
# names(fs) <- fs::path_file(fs::path_ext_remove(fs))
#
# # Run limma voom DE at the individual and broad cell type level
# ict <- h5ad_de(fs = fs, model = ~ age_death + sex + pmi, verbose=T)
# bct <- h5ad_de(fs = fs, model = ~ age_death + sex + pmi, groups_label = c("Ast", "Mic", "Oli", "Inh", "Exc"))
suppressPackageStartupMessages({
library(Matrix)
library(purrr)
library(fs)
library(Libra)
library(stringr)
library(dplyr)
source("~tl3087/utils.R")
})
# Define covariates
if (is.null(model)) {
covs <- replicate_col
} else if (!inherits(model, "formula")) {
stop("Model is not of class formula. Did you forget to add \"~\"?")
} else {
covs <- c(replicate_col, labels(terms(model)))
}
# Define grouping level for DE
if (!is.null(groups_label)) {
if (!all(groups_label %in% stringr::str_extract(fs, groups_label))) {
stop("At least one element in groups_label is not present in fs.")
}
} else {
groups_label <- fs::path_file(fs::path_ext_remove(fs))
}
# Return DE df per group_label
results <- tryCatch(
{
purrr::map_dfr(groups_label, function(g) {
# Extract files matching group label
fs <- fs[stringr::str_detect(fs, stringr::fixed(g))]
# Parse counts and cell-level metadata from h5ads
cts <- purrr::map(fs, get_h5ad)
## Get rid of obs with NAs in any model or ID variable
if (!is.null(model)) {
cts <- purrr::map(cts, ~ {
expr <- .$expr
meta <- .$meta
meta <- meta[complete.cases(meta[, covs]), ]
expr <- expr[, rownames(meta)]
return(list(expr = expr, meta = meta))
})
}
# Filter to specified replicate_col labels
if (!is.null(replicate_col_ids)) {
cts <- purrr::map(cts, ~ {
expr <- .$expr
meta <- .$meta
if (class(meta[[replicate_col]]) != class(replicate_col_ids)) {
stop("Make sure replicate_col_ids has the same class as replicate_col.")
}
meta <- meta[meta[[replicate_col]] %in% replicate_col_ids, ]
expr <- expr[, rownames(meta)]
return(list(expr = expr, meta = meta))
})
}
# Pseudobulk each sparse matrix
if (verbose) {
message("Pseudobulking...")
}
cts <- purrr::map(cts, ~ {
ps <- tryCatch(
{
Libra::to_pseudobulk(
.$expr,
meta = .$meta,
replicate_col = replicate_col,
cell_type_col = cell_type_col,
label_col = label_col,
model = model
)
},
error = function(e) {
message(e)
list()
}
)
})
# Make sure no extra level of list was created
if (purrr::vec_depth(cts) > 4) {
cts <- purrr::flatten(cts)
}
if (!is.null(groups_label)) {
# Aggregate pseudocounts accross sub cell types
expr <- purrr::reduce(purrr::map(cts, "expr"), ~ {
.x <- as(as.matrix(.x), "sparseMatrix")
.y <- as(as.matrix(.y), "sparseMatrix")
merge.sparse(.x, .y)
})
meta <- purrr::reduce(purrr::map(cts, "meta"), dplyr::union)
cts <- list(list(expr = expr, meta = meta)) %>% setNames(g)
}
# DE
cts_de <- tryCatch(
{
Libra::run_de(
cts,
de_family = de_family,
de_method = de_method,
de_type = de_type,
model = model,
verbose = verbose
)
},
error = function(e) {
message(e)
list()
}
)
return(cts_de)
})
},
error = function(e) {
message(e)
data.frame(
cell_type = NA,
gene = NA,
avg_logFC = NA,
p_val = NA,
bonf = NA,
fdr = NA,
de_family = NA,
de_method = NA,
de_type = NA,
stat = NA,
lfcse = NA
)
}
)
return(results)
}
tidy_rma <- function(x, conf.level = 0.95, exponentiate = FALSE,
include_studies = FALSE, measure = "GEN", ...) {
# Parse output from metafor::rma() into a dataframe
#
# x metafor object produced after running metafor::rma()
# tidy summary estimates
betas <- x$beta
if (!is.null(nrow(betas)) && nrow(betas) > 1) {
# get estimate type and fix spelling
study <- rownames(betas)
swap <- grepl("intrcpt", study)
study[swap] <- "intercept"
betas <- as.double(betas)
} else {
study <- "overall"
betas <- betas[1]
}
if (x$level != 1 - conf.level) {
level <- 1 - conf.level
if (is.element(x$test, c("knha", "adhoc", "t"))) {
crit <- if (all(x$ddf > 0)) qt(level / 2, df = x$ddf, lower.tail = FALSE) else NA
} else {
crit <- qnorm(level / 2, lower.tail = FALSE)
}
conf.low <- c(betas - crit * x$se)
conf.high <- c(betas + crit * x$se)
} else {
conf.low <- x$ci.lb
conf.high <- x$ci.ub
}
results <- tibble::tibble(
estimate = betas,
std_error = x$se,
statistic = x$zval,
p_value = x$pval,
conf_low = conf.low,
conf_high = conf.high,
tau2 = x$tau2,
tau2_se = x$se.tau2,
k = x$k,
p = x$p,
m = x$m,
h2 = x$H2,
qe = x$QE,
qep = x$QEp,
i2 = x$I2,
r2 = x$R2,
ll = x$fit.stats$REML[1],
dev = x$fit.stats$REML[2],
aic = x$fit.stats$REML[3],
bic = x$fit.stats$REML[4],
aicc = x$fit.stats$REML[5],
reoptimize = if (!is.null(x$reoptimize)) x$reoptimize,
sigma2 = if (!is.null(x$sigma2)) x$sigma2
)
# tidy individual studies
if (include_studies) {
# use `metafor::escalc` to standardize estimates and confidence intervals
estimates <- metafor::escalc(yi = x$yi.f, vi = x$vi.f, measure = measure) %>%
summary(level = conf.level * 100) %>%
as.data.frame(stringsAsFactors = FALSE)
n_studies <- length(x$slab)
estimates <- dplyr::bind_cols(
term = as.character(x$slab),
# dplyr::bind_cols is strict about recycling, so repeat for each study
type = rep("study", n_studies),
estimates[, c("yi", "sei", "zi")],
p.value = rep(NA, n_studies),
estimates[, c("ci.lb", "ci.ub")]
)
names(estimates) <- c(
"term", "type", "estimate", "std.error", "statistic",
"p.value", "conf.low", "conf.high"
)
estimates <- as_tibble(estimates)
results <- dplyr::bind_rows(estimates, results)
}
if (exponentiate) {
results <- exponentiate(results)
}
return(results)
}
my_tidy_rma <- function(i, lfcs, seis, measure = "ROM", method = "REML",
verbose = F, ...) {
# Run and format radom effects mixed model meta-analysis with metafor
#
# i character. Meta-analysis unit. e.g. Gene name or cell type.
# lfcs numeric. Vector with log fold change for each study.
# seis numeric. Vector with the standard errors for each study.
# description
# It uses tidy_rma(), a modified version of \code{broom.mixed::tidy.rma()} that extracts more model information than the default.
if (verbose == T & !is.null(i)) {
message(i)
}
x <- tryCatch(
{
# Check for NAs
if (any(is.na(lfcs))) {
na.pos <- which(is.na(lfcs))
lfcs <- lfcs[-na.pos]
seis <- seis[-na.pos]
} else if (any(is.na(seis))) {
na.pos <- which(is.na(seis))
lfcs <- lfcs[-na.pos]
seis <- seis[-na.pos]
}
# Check legths match and there are at least two studies
stopifnot(
length(lfcs) == length(seis),
length(lfcs) > 1
)
# Run meta-analysis
x <- metafor::rma(
yi = lfcs,
sei = seis,
measure = measure,
method = method,
verbose = verbose,
...
)
# Return tidy metafor
return(tidy_rma(x))
},
error = function(e) {
return(
tibble::tibble(
estimate = NA,
std_error = NA,
statistic = NA,
p_value = NA,
conf_low = NA,
conf_high = NA,
tau2 = NA,
tau2_se = NA,
h2 = NA,
qe = NA,
qep = NA,
i2 = NA,
ll = NA,
dev = NA,
aic = NA,
bic = NA,
aicc = NA
)
)
}
)
return(x)
}
influence_to_df <- function(x) {
# Extract the relevant information from the influence object into a data frame
# metafor objects can be diagnosed with this function
data.frame(
rstudent = x$inf$rstudent,
dffits = x$inf$dffits,
cook.d = x$inf$cook.d,
cov.r = x$inf$cov.r,
tau2.del = x$inf$tau2.del,
QE.del = x$inf$QE.del,
hat = x$inf$hat,
weight = x$inf$weight,
dfbs = x$dfbs$intrcpt,
inf = x$is.infl
)
}
rma_with_restart <- function(data, type = "RE", yi_col = "log_fc",
sei_col = "lfcse", slab = NULL) {
#' Perform Meta-Analysis with Restart Logic
#'
#' This function performs meta-analysis with restart logic based on specified models and tests.
#'
#' @param data A data frame containing the relevant variables for the meta-analysis.
#' @param type A character string specifying the type of meta-analysis.
#' Options include "RE" for random effects, "REHSK" for random effects with Hedges' g,
#' and "FE" for fixed effects. Default is "RE".
#' @param yi_col A character string specifying the column name in \code{data} containing
#' the effect sizes (yi) for the meta-analysis. Default is "log_fc".
#' @param sei_col A character string specifying the column name in \code{data} containing
#' the standard errors of the effect sizes (sei) for the meta-analysis. Default is "lfcse".
#' @slab optional vector with labels for the k studies
#'
#' @return A data frame containing the meta-analysis results, including effect size estimates,
#' standard errors, and additional information about the optimization process.
#'
#' @examples
#' # Example data
#' data <- tibble::tibble(
#' race_eth = c("H", "NHAA", "NHW"),
#' estimate = c(-0.0176, -0.162, -0.0537),
#' std.error = c(0.415, 0.245, 0.326),
#' statistic = c(-0.0424, -0.658, -0.165),
#' p.value = c(0.967, 0.515, 0.870)
#' )
#' # Example usage:
#' result <- rma_with_restart(data, type = "RE", yi_col = "log_fc", sei_col = "lfcse", slab = "race_eth")
#' result$reoptimize
#'
#' @references
#' Viechtbauer, W. (2010). Conducting meta-analyses in R with the metafor package.
#' Journal of Statistical Software, 36(3), 1-48.
#'
#' @export
# Define helper function to optimize model
optimize_model <- function(method, test, control = NULL, slab = slab) {
args <- list(
yi = data[[yi_col]],
sei = data[[sei_col]],
method = method,
test = test,
control = control,
slab = slab
)
# Remove NULL elements from the argument list
args <- args[!sapply(args, is.null)]
# Use do.call to invoke the function
res <- do.call(metafor::rma, args)
if (!inherits(res, "try-error")) {
res$reoptimize <- paste(tolower(method), test, sep = "_")
} else {
message(paste("Error in optimization for method:", method, "and test:", test))
res <- NULL
}
res
}
# Check if yi_col and sei_col exist in data
if (!yi_col %in% colnames(data) | !sei_col %in% colnames(data)) {
stop("Columns yi_col and sei_col must exist in the data.")
}
# Define optimization settings based on the type
if (type == "RE") {
methods <- c("REML", "REML", "ML", "FE")
tests <- c("knha", "knha", "knha", "t")
controls <- list(NULL, list(maxiter = 10000, stepadj = 0.5), NULL, NULL)
} else if (type == "REHSK") {
methods <- c("HSk", "HS", "HE", "SJ")
tests <- c("knha", "knha", "knha", "knha")
controls <- rep(list(NULL), 4)
} else if (type == "FE") {
methods <- c("FE", "FE", "FE")
tests <- c("t", "t", "z")
controls <- list(NULL, list(maxiter = 10000, stepadj = 0.5), NULL)
}
# Iterate over methods and tests to find the first successful optimization
for (i in seq_along(methods)) {
current_result <- optimize_model(methods[i], tests[i], controls[[i]],
slab = slab)
if (!is.null(current_result)) break
}
current_result
}
rma_with_diagnostics <- function(data, key = NULL, study_col = NULL,
yi_col = NULL, sei_col = NULL,
type = "RE") {
#' Perform Meta-Analysis with Diagnostics
#'
#' Conducts a meta-analysis using the rma_with_restart function and provides various diagnostics, including leave-one-out results, outlier detection,
#' and residuals.
#'
#' @param data A data frame containing the relevant variables for the meta-analysis.
#' @param key A character string specifying the key variable in the data.
#' @param study_col A character string specifying the column name in data containing
#' the study identifiers.
#' @param yi_col A character string specifying the column name in data containing
#' the effect sizes (yi) for the meta-analysis.
#' @param sei_col A character string specifying the column name in data containing
#' the standard errors of the effect sizes (sei) for the meta-analysis.
#' @param type A character string specifying the type of meta-analysis.
#' Options include "RE" for random effects, "REHSK" for random effects with Hedges' g, and "FE" for fixed effects. Default is "RE".
#'
#' @return A data frame containing the meta-analysis results, including effect size estimates,
#' standard errors, and additional information about the optimization process.
#'
#' @examples
#' # Example usage:
#' # Example data
#' data <- tibble::tibble(
#' region = c("AC"),
#' variable = c("braaksc_cat"),
#' term = c("Braak3"),
#' cell_type = c("Astro"),
#' yis_and_seis = list(tibble::tibble(
#' race_eth = c("H", "NHAA", "NHW"),
#' estimate = c(-0.0176, -0.162, -0.0537),
#' std.error = c(0.415, 0.245, 0.326),
#' statistic = c(-0.0424, -0.658, -0.165),
#' p.value = c(0.967, 0.515, 0.870),
#' conf.low = c(-0.872, -0.652, -0.685),
#' conf.high = c(0.767, 0.313, 0.598)
#' ))
#' )
#' result <- rma_with_diagnostics(data, key = "yis_and_seis",
#' study_col = "race_eth", yi_col = "estimate", sei_col = "std.error")
#' print(result)
#'
#' @references
#' Viechtbauer, W. (2010). Conducting meta-analyses in R with the metafor package.
#' Journal of Statistical Software, 36(3), 1-48.
#'
#' @export
if (!key %in% colnames(data)) stop("Column key must exist in the data.")
key_col_names <- colnames(data[[key]][[1]])
if (any(!c(study_col, yi_col, sei_col) %in% key_col_names)) {
stop("Columns study_col, yi_col, and sei_col must exist in the key list column.")
}
# Run meta-analysis safely
safe_rma <- purrr::compose(
purrr::list_flatten,
purrr::safely(purrr::quietly(rma_with_restart))
)
tictoc::tic.clear()
tictoc::tic("Total")
tictoc::tic("Running meta-analysis")
res <- data %>%
dplyr::mutate(
# Run meta-analysis safely
rma_result = purrr::map(
!!rlang::sym(key),
~ safe_rma(.x, type, yi_col, sei_col, .x[[study_col]])
),
# Extract error
error = purrr::map_chr(
rma_result,
~ ifelse(!is.null(.x$error),
as.character(.x$error$message), NA)
),
warning = purrr::map_chr(
rma_result,
~ ifelse(!is.null(.x$result_warnings),
as.character(.x$result_warnings), NA)
),
messages = purrr::map_chr(
rma_result,
~ ifelse(!is.null(.x$result_messages),
as.character(.x$result_messages), NA)
),
# Extract results
rma = purrr::map(rma_result, "result_result"),
# Wider per-study effects
purrr::map_dfr(
!!rlang::sym(key),
~ .x %>%
tidyr::pivot_wider(
names_from = !!rlang::sym(study_col),