-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathmethods.R
executable file
·4993 lines (4361 loc) · 163 KB
/
methods.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
setOldClass("tidybulk")
#' Creates an annotated `tidybulk` tibble from a `tbl` or `SummarizedExperiment` object
#'
#' `r lifecycle::badge("maturing")`
#'
#' @description tidybulk() creates an annotated `tidybulk` tibble from a `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment))
#'
#' @importFrom rlang enquo
#' @importFrom rlang quo_is_missing
#'
#' @import readr
#' @import SummarizedExperiment
#' @import methods
#'
#' @name tidybulk
#'
#' @param .data A `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment))
#' @param .sample The name of the sample column
#' @param .transcript The name of the transcript/gene column
#' @param .abundance The name of the transcript/gene abundance column
#' @param .abundance_scaled The name of the transcript/gene scaled abundance column
#'
#' @details This function creates a tidybulk object and is useful if you want
#' to avoid to specify .sample, .transcript and .abundance arguments all the times.
#' The tidybulk object have an attribute called internals where these three
#' arguments are stored as metadata. They can be extracted as attr(<object>, "internals").
#'
#' @return A `tidybulk` object
#'
#'
#' @examples
#'
#' tidybulk(tidybulk::se_mini)
#'
#'
#' @docType methods
#' @rdname tidybulk-methods
#'
#' @export
#'
setGeneric("tidybulk", function(.data,
.sample,
.transcript,
.abundance,
.abundance_scaled = NULL)
standardGeneric("tidybulk"))
# Set internal
.tidybulk = function(.data,
.sample,
.transcript,
.abundance,
.abundance_scaled = NULL) {
# Make col names
.sample = enquo(.sample)
.transcript = enquo(.transcript)
.abundance = enquo(.abundance)
.abundance_scaled = enquo(.abundance_scaled)
if(
quo_is_missing(.sample) |
quo_is_missing(.transcript) |
quo_is_missing(.abundance)
) stop("tidybulk says: the arguments .sample, .transcript and .abundance must include column names (not surrounded by quotes)")
# Validate data frame
if(do_validate()) validation(.data,
!!.sample,
!!.transcript,
!!.abundance,
skip_dupli_check = TRUE)
create_tt_from_tibble_bulk(.data,
!!.sample,
!!.transcript,
!!.abundance,
!!.abundance_scaled)
}
#' tidybulk
#'
#' @export
#'
#' @inheritParams tidybulk
#'
#' @docType methods
#' @rdname tidybulk-methods
#'
#' @return A `tidybulk` object
#'
setMethod("tidybulk", "spec_tbl_df", .tidybulk)
#' tidybulk
#'
#' @export
#'
#' @importFrom purrr map2
#'
#' @inheritParams tidybulk
#'
#' @docType methods
#' @rdname tidybulk-methods
#'
#' @return A `tidybulk` object
#'
setMethod("tidybulk", "tbl_df", .tidybulk)
#' as_SummarizedExperiment
#'
#' @description as_SummarizedExperiment() creates a `SummarizedExperiment` object from a `tbl` or `tidybulk` tbl formatted as | <SAMPLE> | <TRANSCRIPT> | <COUNT> | <...> |
#'
#'
#' @importFrom utils data
#' @importFrom tidyr pivot_longer
#'
#' @param .data A tibble
#' @param .sample The name of the sample column
#' @param .transcript The name of the transcript/gene column
#' @param .abundance The name of the transcript/gene abundance column
#'
#' @return A `SummarizedExperiment` object
#'
#' @docType methods
#' @rdname as_SummarizedExperiment-methods
#' @export
#'
setGeneric("as_SummarizedExperiment", function(.data,
.sample = NULL,
.transcript = NULL,
.abundance = NULL)
standardGeneric("as_SummarizedExperiment"))
.as_SummarizedExperiment = function(.data,
.sample = NULL,
.transcript = NULL,
.abundance = NULL) {
# Fix NOTEs
. = NULL
# Get column names
.sample = enquo(.sample)
.transcript = enquo(.transcript)
.abundance = enquo(.abundance)
col_names = get_sample_transcript_counts(.data, .sample, .transcript, .abundance)
.sample = col_names$.sample
.transcript = col_names$.transcript
.abundance = col_names$.abundance
# Check if package is installed, otherwise install
check_and_install_packages(c("SummarizedExperiment", "S4Vectors"))
# If present get the scaled abundance
.abundance_scaled =
.data %>%
ifelse_pipe(
".abundance_scaled" %in% ((.) %>% get_tt_columns() %>% names) &&
# .data %>% get_tt_columns() %$% .abundance_scaled %>% is.null %>% not() &&
quo_name((.) %>% get_tt_columns() %$% .abundance_scaled) %in% ((.) %>% colnames),
~ .x %>% get_tt_columns() %$% .abundance_scaled,
~ NULL
)
# Get which columns are sample wise and which are feature wise
col_direction = get_x_y_annotation_columns(.data,
!!.sample,
!!.transcript,
!!.abundance,
!!.abundance_scaled)
sample_cols = col_direction$horizontal_cols
feature_cols = col_direction$vertical_cols
counts_cols = col_direction$counts_cols
colData =
.data %>%
select(!!.sample, sample_cols) %>%
distinct() %>%
# Unite if multiple sample columns
tidyr::unite(!!sample__$name, !!.sample, remove = FALSE, sep = "___") |>
arrange(!!sample__$symbol) %>% {
S4Vectors::DataFrame(
(.) %>% select(-!!sample__$symbol),
row.names = (.) %>% pull(!!sample__$symbol)
)
}
rowData =
.data %>%
select(!!.transcript, feature_cols) %>%
distinct() %>%
# Unite if multiple sample columns
tidyr::unite(!!feature__$name, !!.transcript, remove = FALSE, sep = "___") |>
arrange(!!feature__$symbol) %>% {
S4Vectors::DataFrame(
(.) %>% select(-!!feature__$symbol),
row.names = (.) %>% pull(!!feature__$symbol)
)
}
my_assays =
.data %>%
# Unite if multiple sample columns
tidyr::unite(!!sample__$name, !!.sample, remove = FALSE, sep = "___") |>
# Unite if multiple sample columns
tidyr::unite(!!feature__$name, !!.transcript, remove = FALSE, sep = "___") |>
select(!!sample__$symbol,
!!feature__$symbol,
!!.abundance,
!!.abundance_scaled,
counts_cols) %>%
distinct() %>%
pivot_longer( cols=-c(!!feature__$symbol,!!sample__$symbol), names_to="assay", values_to= ".a") %>%
nest(`data` = -`assay`) %>%
mutate(`data` = `data` %>% map(
~ .x %>%
spread(!!sample__$symbol, .a) %>%
# arrange sample
select(!!feature__$symbol, rownames(colData)) |>
# Arrange symbol
arrange(!!feature__$symbol) |>
# Convert
as_matrix(rownames = feature__$name)
))
# Build the object
SummarizedExperiment::SummarizedExperiment(
assays = my_assays %>% pull(`data`) %>% setNames(my_assays$assay),
rowData = rowData,
colData = colData
)
}
#' as_SummarizedExperiment
#'
#' @export
#'
#' @inheritParams as_SummarizedExperiment
#'
#' @docType methods
#' @rdname as_SummarizedExperiment-methods
#'
#' @return A `SummarizedExperiment` object
#'
setMethod("as_SummarizedExperiment", "spec_tbl_df", .as_SummarizedExperiment)
#' as_SummarizedExperiment
#'
#' @export
#'
#' @inheritParams as_SummarizedExperiment
#'
#' @docType methods
#' @rdname as_SummarizedExperiment-methods
#'
#' @return A `SummarizedExperiment` object
#'
setMethod("as_SummarizedExperiment", "tbl_df", .as_SummarizedExperiment)
#' as_SummarizedExperiment
#'
#' @export
#'
#' @inheritParams as_SummarizedExperiment
#'
#' @docType methods
#' @rdname as_SummarizedExperiment-methods
#'
#' @return A `SummarizedExperiment` object
#'
setMethod("as_SummarizedExperiment", "tidybulk", .as_SummarizedExperiment)
#' Creates a `tt` object from a list of file names of BAM/SAM
#'
#' `r lifecycle::badge("maturing")`
#'
#' @description tidybulk_SAM_BAM() creates a `tt` object from A `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment))
#'
#' @importFrom rlang enquo
#'
#'
#' @name tidybulk_SAM_BAM
#'
#' @param file_names A character vector
#' @param genome A character string specifying an in-built annotation used for read summarization. It has four possible values including "mm10", "mm9", "hg38" and "hg19"
#' @param ... Further parameters passed to the function Rsubread::featureCounts
#'
#' @details This function is based on FeatureCounts package (DOI: 10.1093/bioinformatics/btt656). This function creates a tidybulk object and is useful if you want
#' to avoid to specify .sample, .transcript and .abundance arguments all the times.
#' The tidybulk object have an attribute called internals where these three
#' arguments are stored as metadata. They can be extracted as attr(<object>, "internals").
#'
#' Underlying core function
#' Rsubread::featureCounts(annot.inbuilt = genome,nthreads = n_cores, ...)
#'
#' @return A `tidybulk` object
#'
#'
#'
#'
#'
#' @docType methods
#' @rdname tidybulk_SAM_BAM-methods
#' @export
#'
setGeneric("tidybulk_SAM_BAM", function(file_names, genome = "hg38", ...)
standardGeneric("tidybulk_SAM_BAM"))
#' tidybulk_SAM_BAM
#'
#' @export
#'
#' @inheritParams tidybulk_SAM_BAM-methods
#'
#' @docType methods
#' @rdname tidybulk_SAM_BAM-methods
#'
#' @return A `tidybulk` object
#'
setMethod("tidybulk_SAM_BAM", c(file_names = "character", genome = "character"), function(file_names, genome = "hg38", ...)
create_tt_from_bam_sam_bulk(file_names = file_names, genome = genome, ...))
#' Scale the counts of transcripts/genes
#'
#' `r lifecycle::badge("maturing")`
#'
#' @description scale_abundance() takes as input A `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment)) and Scales transcript abundance compansating for sequencing depth (e.g., with TMM algorithm, Robinson and Oshlack doi.org/10.1186/gb-2010-11-3-r25).
#'
#' @importFrom rlang enquo
#'
#' @importFrom stats median
#'
#' @name scale_abundance
#'
#' @param .data A `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment))
#' @param .sample The name of the sample column
#' @param .transcript The name of the transcript/gene column
#' @param .abundance The name of the transcript/gene abundance column
#' @param method A character string. The scaling method passed to the back-end function (i.e., edgeR::calcNormFactors; "TMM","TMMwsp","RLE","upperquartile")
#' @param reference_sample A character string. The name of the reference sample. If NULL the sample with highest total read count will be selected as reference.
#' @param .subset_for_scaling A gene-wise quosure condition. This will be used to filter rows (features/genes) of the dataset. For example
#' @param action A character string between "add" (default) and "only". "add" joins the new information to the input tbl (default), "only" return a non-redundant tbl with the just new information.
#'
#' @param reference_selection_function DEPRECATED. please use reference_sample.
#'
#' @details Scales transcript abundance compensating for sequencing depth
#' (e.g., with TMM algorithm, Robinson and Oshlack doi.org/10.1186/gb-2010-11-3-r25).
#' Lowly transcribed transcripts/genes (defined with minimum_counts and minimum_proportion parameters)
#' are filtered out from the scaling procedure.
#' The scaling inference is then applied back to all unfiltered data.
#'
#' Underlying method
#' edgeR::calcNormFactors(.data, method = c("TMM","TMMwsp","RLE","upperquartile"))
#'
#'
#'
#' @return A tbl object with additional columns with scaled data as `<NAME OF COUNT COLUMN>_scaled`
#'
#'
#' @examples
#'
#'
#' tidybulk::se_mini |>
#' identify_abundant() |>
#' scale_abundance()
#'
#'
#'
#' @docType methods
#' @rdname scale_abundance-methods
#' @export
setGeneric("scale_abundance", function(.data,
.sample = NULL,
.transcript = NULL,
.abundance = NULL,
method = "TMM",
reference_sample = NULL,
.subset_for_scaling = NULL,
action = "add",
# DEPRECATED
reference_selection_function = NULL)
standardGeneric("scale_abundance"))
# Set internal
.scale_abundance = function(.data,
.sample = NULL,
.transcript = NULL,
.abundance = NULL,
method = "TMM",
reference_sample = NULL,
.subset_for_scaling = NULL,
action = "add",
# DEPRECATED
reference_selection_function = NULL)
{
# Fix NOTEs
. = NULL
# Get column names
.sample = enquo(.sample)
.transcript = enquo(.transcript)
.abundance = enquo(.abundance)
col_names = get_sample_transcript_counts(.data, .sample, .transcript, .abundance)
.sample = col_names$.sample
.transcript = col_names$.transcript
.abundance = col_names$.abundance
.subset_for_scaling = enquo(.subset_for_scaling)
# Set column name for value scaled
value_scaled = as.symbol(sprintf("%s%s", quo_name(.abundance), scaled_string))
# DEPRECATION OF reference function
if (is_present(reference_selection_function) & !is.null(reference_selection_function)) {
# Signal the deprecation to the user
deprecate_warn("1.1.8", "tidybulk::scale_abundance(reference_selection_function = )", details = "The argument reference_selection_function is now deprecated please use reference_sample. By default the reference selection function is max()")
}
# Validate data frame
if(do_validate()) {
validation(.data, !!.sample, !!.transcript, !!.abundance)
warning_if_data_is_not_rectangular(.data, !!.sample, !!.transcript, !!.abundance)
}
# Check that reference sample exists
if(!is.null(reference_sample) && !reference_sample %in% (.data %>% pull(!!.sample)))
stop("tidybulk says: your reference sample is not among the samples in your data frame")
.data_norm =
.data %>%
# Filter abundant if performed
when(
".abundant" %in% colnames(.) ~ filter(., .abundant),
~ {
warning("tidybulk says: highly abundant transcripts were not identified (i.e. identify_abundant()) or filtered (i.e., keep_abundant), therefore this operation will be performed on unfiltered data. In rare occasions this could be wanted. In standard whole-transcriptome workflows is generally unwanted.")
(.)
}
) %>%
# filter based on user selection
when(
!quo_is_null(.subset_for_scaling) ~ filter(., !!.subset_for_scaling),
~ (.)
) %>%
# Check I have genes left
when(nrow(.) == 0 ~ stop("tidybulk says: there are 0 genes that passes the filters (.abundant and/or .subset_for_scaling). Please check your filtering or your data."), ~ (.)) %>%
get_scaled_counts_bulk(
.sample = !!.sample,
.transcript = !!.transcript,
.abundance = !!.abundance,
method = method,
reference_sample = reference_sample
) %>%
# Attach column internals
add_tt_columns(
!!(.sample |> drop_enquo_env()),
!!(.transcript |> drop_enquo_env()),
!!(.abundance |> drop_enquo_env()),
!!(((function(x, v) enquo(v))(x,!!value_scaled)) |> drop_enquo_env())
)
if (action == "add"){
.data %>%
left_join(.data_norm, by=quo_name(.sample)) %>%
dplyr::mutate(!!value_scaled := !!.abundance * multiplier) %>%
# Attach attributes
reattach_internals(.data_norm)
}
else if (action == "get"){
.data %>%
# Selecting the right columns
pivot_sample(!!.sample) %>%
# Join result
left_join(.data_norm, by=quo_name(.sample)) %>%
# Attach attributes
reattach_internals(.data_norm)
}
else if (action == "only") .data_norm
else
stop(
"tidybulk says: action must be either \"add\" for adding this information to your data frame or \"get\" to just get the information"
)
}
#' scale_abundance
#'
#' @export
#'
#' @inheritParams scale_abundance
#'
#' @docType methods
#' @rdname scale_abundance-methods
#'
#' @return A tbl object with additional columns with scaled data as `<NAME OF COUNT COLUMN>_scaled`
#'
setMethod("scale_abundance", "spec_tbl_df", .scale_abundance)
#' scale_abundance
#'
#' @export
#'
#' @inheritParams scale_abundance
#'
#' @docType methods
#' @rdname scale_abundance-methods
#'
#' @return A tbl object with additional columns with scaled data as `<NAME OF COUNT COLUMN>_scaled`
#'
setMethod("scale_abundance", "tbl_df", .scale_abundance)
#' scale_abundance
#'
#' @export
#'
#' @inheritParams scale_abundance
#'
#' @docType methods
#' @rdname scale_abundance-methods
#'
#' @return A tbl object with additional columns with scaled data as `<NAME OF COUNT COLUMN>_scaled`
#'
setMethod("scale_abundance", "tidybulk", .scale_abundance)
#' Normalise by quantiles the counts of transcripts/genes
#'
#' `r lifecycle::badge("maturing")`
#'
#' @description quantile_normalise_abundance() takes as input A `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment)) and Scales transcript abundance compansating for sequencing depth (e.g., with TMM algorithm, Robinson and Oshlack doi.org/10.1186/gb-2010-11-3-r25).
#'
#' @importFrom rlang enquo
#'
#' @importFrom stats median
#' @importFrom dplyr join_by
#'
#' @name quantile_normalise_abundance
#'
#' @param .data A `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment))
#' @param .sample The name of the sample column
#' @param .transcript The name of the transcript/gene column
#' @param .abundance The name of the transcript/gene abundance column
#' @param method A character string. Either "limma_normalize_quantiles" for limma::normalizeQuantiles or "preprocesscore_normalize_quantiles_use_target" for preprocessCore::normalize.quantiles.use.target for large-scale datasets.
#' @param target_distribution A numeric vector. If NULL the target distribution will be calculated by preprocessCore. This argument only affects the "preprocesscore_normalize_quantiles_use_target" method.
#' @param action A character string between "add" (default) and "only". "add" joins the new information to the input tbl (default), "only" return a non-redundant tbl with the just new information.
#'
#'
#' @details Tranform the feature abundance across samples so to have the same quantile distribution (using preprocessCore).
#'
#' Underlying method
#'
#' If `limma_normalize_quantiles` is chosen
#'
#' .data |>limma::normalizeQuantiles()
#'
#' If `preprocesscore_normalize_quantiles_use_target` is chosen
#'
#' .data |>
#' preprocessCore::normalize.quantiles.use.target(
#' target = preprocessCore::normalize.quantiles.determine.target(.data)
#' )
#'
#'
#' @return A tbl object with additional columns with scaled data as `<NAME OF COUNT COLUMN>_scaled`
#'
#'
#' @examples
#'
#'
#' tidybulk::se_mini |>
#' quantile_normalise_abundance()
#'
#'
#'
#' @docType methods
#' @rdname quantile_normalise_abundance-methods
#' @export
setGeneric("quantile_normalise_abundance", function(.data,
.sample = NULL,
.transcript = NULL,
.abundance = NULL,
method = "limma_normalize_quantiles",
target_distribution = NULL,
action = "add")
standardGeneric("quantile_normalise_abundance"))
# Set internal
.quantile_normalise_abundance = function(.data,
.sample = NULL,
.transcript = NULL,
.abundance = NULL,
method = "limma_normalize_quantiles",
target_distribution = NULL,
action = "add")
{
# Fix NOTEs
. = NULL
# Get column names
.sample = enquo(.sample)
.transcript = enquo(.transcript)
.abundance = enquo(.abundance)
col_names = get_sample_transcript_counts(.data, .sample, .transcript, .abundance)
.sample = col_names$.sample
.transcript = col_names$.transcript
.abundance = col_names$.abundance
# Set column name for value scaled
value_scaled = as.symbol(sprintf("%s%s", quo_name(.abundance), scaled_string))
# Reformat input data set
.data_norm <-
.data %>%
# Rename
dplyr::select(!!.sample,!!.transcript,!!.abundance) %>%
# Set samples and genes as factors
dplyr::mutate(!!.sample := factor(!!.sample),!!.transcript := factor(!!.transcript)) |>
pivot_wider(names_from = !!.sample, values_from = !!.abundance) |>
as_matrix(rownames=!!.transcript)
if(tolower(method) == "limma_normalize_quantiles"){
# Check if package is installed, otherwise install
check_and_install_packages("limma")
.data_norm =
.data_norm |>
limma::normalizeQuantiles()
}
else if(tolower(method) == "preprocesscore_normalize_quantiles_use_target"){
# Check if package is installed, otherwise install
check_and_install_packages("preprocessCore")
if(is.null(target_distribution)) target_distribution = preprocessCore::normalize.quantiles.determine.target(.data_norm)
.data_norm_quant =
.data_norm |>
preprocessCore::normalize.quantiles.use.target(
target = target_distribution
)
colnames(.data_norm_quant) = .data_norm |> colnames()
rownames(.data_norm_quant) = .data_norm |> rownames()
.data_norm = .data_norm_quant
rm(.data_norm_quant)
} else stop("tidybulk says: the methods must be limma_normalize_quantiles or preprocesscore")
.data_norm =
.data_norm |>
as_tibble(rownames = quo_name(.transcript)) |>
pivot_longer(-!!.transcript, names_to = quo_name(.sample), values_to = quo_names(value_scaled)) |>
# Attach column internals
add_tt_columns(
!!(.sample |> drop_enquo_env()),
!!(.transcript |> drop_enquo_env()),
!!(.abundance |> drop_enquo_env()),
!!(((function(x, v) enquo(v))(x,!!value_scaled)) |> drop_enquo_env())
)
if (action %in% c( "add", "get")){
.data %>%
left_join(.data_norm, by= join_by(!!.sample, !!.transcript)) %>%
# Attach attributes
reattach_internals(.data_norm) |>
# Add methods
memorise_methods_used(c("quantile"))
}
else if (action == "only") .data_norm
else
stop(
"tidybulk says: action must be either \"add\" for adding this information to your data frame or \"get\" to just get the information"
)
}
#' quantile_normalise_abundance
#'
#' @export
#'
#' @inheritParams quantile_normalise_abundance
#'
#' @docType methods
#' @rdname quantile_normalise_abundance-methods
#'
#' @return A tbl object with additional columns with scaled data as `<NAME OF COUNT COLUMN>_scaled`
#'
setMethod("quantile_normalise_abundance", "spec_tbl_df", .quantile_normalise_abundance)
#' quantile_normalise_abundance
#'
#' @export
#'
#' @inheritParams quantile_normalise_abundance
#'
#' @docType methods
#' @rdname quantile_normalise_abundance-methods
#'
#' @return A tbl object with additional columns with scaled data as `<NAME OF COUNT COLUMN>_scaled`
#'
setMethod("quantile_normalise_abundance", "tbl_df", .quantile_normalise_abundance)
#' quantile_normalise_abundance
#'
#' @export
#'
#' @inheritParams quantile_normalise_abundance
#'
#' @docType methods
#' @rdname quantile_normalise_abundance-methods
#'
#' @return A tbl object with additional columns with scaled data as `<NAME OF COUNT COLUMN>_scaled`
#'
setMethod("quantile_normalise_abundance", "tidybulk", .quantile_normalise_abundance)
#' Get clusters of elements (e.g., samples or transcripts)
#'
#' `r lifecycle::badge("maturing")`
#'
#' @description cluster_elements() takes as input A `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment)) and identify clusters in the data.
#'
#' @importFrom rlang enquo
#'
#'
#' @name cluster_elements
#'
#' @param .data A `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment))
#' @param .element The name of the element column (normally samples).
#' @param .feature The name of the feature column (normally transcripts/genes)
#' @param .abundance The name of the column including the numerical value the clustering is based on (normally transcript abundance)
#'
#' @param method A character string. The cluster algorithm to use, at the moment k-means is the only algorithm included.
#' @param of_samples A boolean. In case the input is a tidybulk object, it indicates Whether the element column will be sample or transcript column
#' @param transform A function that will tranform the counts, by default it is log1p for RNA sequencing data, but for avoinding tranformation you can use identity
#' @param action A character string. Whether to join the new information to the input tbl (add), or just get the non-redundant tbl with the new information (get).
#' @param ... Further parameters passed to the function kmeans
#'
#' @param log_transform DEPRECATED - A boolean, whether the value should be log-transformed (e.g., TRUE for RNA sequencing data)
#'
#' @details identifies clusters in the data, normally of samples.
#' This function returns a tibble with additional columns for the cluster annotation.
#' At the moment only k-means (DOI: 10.2307/2346830) and SNN clustering (DOI:10.1016/j.cell.2019.05.031) is supported, the plan is to introduce more clustering methods.
#'
#' Underlying method for kmeans
#' do.call(kmeans(.data, iter.max = 1000, ...)
#'
#' Underlying method for SNN
#' .data %>%
#' Seurat::CreateSeuratObject() %>%
#' Seurat::ScaleData(display.progress = TRUE,num.cores = 4, do.par = TRUE) %>%
#' Seurat::FindVariableFeatures(selection.method = "vst") %>%
#' Seurat::RunPCA(npcs = 30) %>%
#' Seurat::FindNeighbors() %>%
#' Seurat::FindClusters(method = "igraph", ...)
#'
#'
#' @return A tbl object with additional columns with cluster labels
#'
#'
#' @examples
#'
#'
#' cluster_elements(tidybulk::se_mini, centers = 2, method="kmeans")
#'
#' @docType methods
#' @rdname cluster_elements-methods
#' @export
#'
setGeneric("cluster_elements", function(.data,
.element = NULL,
.feature = NULL,
.abundance = NULL,
method,
of_samples = TRUE,
transform = log1p,
action = "add",
...,
# DEPRECATED
log_transform = NULL
)
standardGeneric("cluster_elements"))
# Set internal
.cluster_elements = function(.data,
.element = NULL,
.feature = NULL,
.abundance = NULL,
method ,
of_samples = TRUE,
transform = log1p,
action = "add",
...,
# DEPRECATED
log_transform = NULL
)
{
# Fix NOTEs
. = NULL
# DEPRECATION OF log_transform
if (is_present(log_transform) & !is.null(log_transform)) {
# Signal the deprecation to the user
deprecate_warn("1.7.4", "tidybulk::test_differential_abundance(log_transform = )", details = "The argument log_transform is now deprecated, please use transform.")
if(log_transform == TRUE) transform = log1p
}
# Get column names
.element = enquo(.element)
.feature = enquo(.feature)
col_names = get_elements_features(.data, .element, .feature, of_samples)
.element = col_names$.element
.feature = col_names$.feature
# Get scaled abundance if present, otherwise get abundance
.abundance = enquo(.abundance)
col_names = get_abundance_norm_if_exists(.data, .abundance)
.abundance = col_names$.abundance
# Validate data frame
if(do_validate()) {
validation(.data, !!.element, !!.feature, !!.abundance)
error_if_data_is_not_rectangular(.data, !!.element, !!.feature, !!.abundance)
}
.data_procesed =
.data %>%
# Filter abundant if performed
when(
".abundant" %in% colnames(.) ~ filter(., .abundant),
~ {
warning("tidybulk says: highly abundant transcripts were not identified (i.e. identify_abundant()) or filtered (i.e., keep_abundant), therefore this operation will be performed on unfiltered data. In rare occasions this could be wanted. In standard whole-transcriptome workflows is generally unwanted.")
(.)
}
) %>%
# Choose algorithm
when(
method == "kmeans" ~ get_clusters_kmeans_bulk(.,
.abundance = !!.abundance,
.element = !!.element,
.feature = !!.feature,
of_samples = of_samples,
transform = transform,
...
),
method == "SNN" ~ stop("tidybulk says: Matrix package (v1.3-3) causes an error with Seurat::FindNeighbors used in this method. We are trying to solve this issue. At the moment this option in unaviable."),
# get_clusters_SNN_bulk(.,
# .abundance = !!.abundance,
# .element = !!.element,
# .feature = !!.feature,
# of_samples = of_samples,
# transform = transform,
# ...
# ),
TRUE ~ stop("tidybulk says: the only supported methods are \"kmeans\" or \"SNN\" ")
)
# Actions
if (action == "add"){
.data |>
dplyr::left_join( .data_procesed, by=quo_name(.element) ) |>
# Attach attributes
reattach_internals(.data)
}
else if (action == "get"){
.data |>
# Selecting the right columns
pivot_sample(!!.element) |>
dplyr::left_join( .data_procesed, by=quo_name(.element) ) |>
# Attach attributes
reattach_internals(.data)
}
else if (action == "only") .data_procesed
else
stop(
"tidybulk says: action must be either \"add\" for adding this information to your data frame or \"get\" to just get the information"
)
}
#' cluster_elements
#' @inheritParams cluster_elements
#'
#' @docType methods
#' @rdname cluster_elements-methods
#'
#' @return A tbl object with additional columns with cluster labels
#'
setMethod("cluster_elements", "spec_tbl_df", .cluster_elements)
#' cluster_elements
#' @inheritParams cluster_elements
#'
#' @docType methods
#' @rdname cluster_elements-methods
#'
#' @return A tbl object with additional columns with cluster labels
#'
setMethod("cluster_elements", "tbl_df", .cluster_elements)
#' cluster_elements
#' @inheritParams cluster_elements
#'
#' @docType methods
#' @rdname cluster_elements-methods
#'
#' @return A tbl object with additional columns with cluster labels
#'
setMethod("cluster_elements", "tidybulk", .cluster_elements)
#' Dimension reduction of the transcript abundance data
#'
#' `r lifecycle::badge("maturing")`
#'
#' @description reduce_dimensions() takes as input A `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment)) and calculates the reduced dimensional space of the transcript abundance.
#'
#' @importFrom rlang enquo
#'
#'
#' @name reduce_dimensions
#'
#' @param .data A `tbl` (with at least three columns for sample, feature and transcript abundance) or `SummarizedExperiment` (more convenient if abstracted to tibble with library(tidySummarizedExperiment))
#' @param .element The name of the element column (normally samples).
#' @param .feature The name of the feature column (normally transcripts/genes)
#' @param .abundance The name of the column including the numerical value the clustering is based on (normally transcript abundance)
#'