-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDifferentialMetaboliteAnalysis.R
1908 lines (1641 loc) · 100 KB
/
DifferentialMetaboliteAnalysis.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
## ---------------------------
##
## Script name: DMA
##
## Purpose of script: Differential Metabolomics Analysis
##
## Author: Dimitrios Prymidis and Christina Schmidt
##
## Date Created: 2022-10-28
##
## Copyright (c) Dimitrios Prymidis and Christina Schmidt
## Email:
##
## ---------------------------
##
## Notes:
##
##
## ---------------------------
########################################################
### ### ### Differential Metabolite Analysis ### ### ###
########################################################
#' This function allows you to perform differential metabolite analysis to obtain a Log2FC, pval, padj and tval comparing two or multiple conditions.
#'
#' @param InputData DF with unique sample identifiers as row names and metabolite numerical values in columns with metabolite identifiers as column names. Use NA for metabolites that were not detected.
#' @param SettingsFile_Sample DF which contains metadata information about the samples, which will be combined with your input data based on the unique sample identifiers used as rownames.
#' @param SettingsInfo \emph{Optional: } Named vector including the information about the conditions column information on numerator or denominator c(Conditions="ColumnName_SettingsFile", Numerator = "ColumnName_SettingsFile", Denominator = "ColumnName_SettingsFile"). Denominator and Numerator will specify which comparison(s) will be done (one-vs-one, all-vs-one, all-vs-all), e.g. Denominator=NULL and Numerator =NULL selects all the condition and performs multiple comparison all-vs-all. Log2FC are obtained by dividing the numerator by the denominator, thus positive Log2FC values mean higher expression in the numerator. \strong{Default = c(conditions="Conditions", numerator = NULL, denumerator = NULL)}
#' @param StatPval \emph{Optional: } String which contains an abbreviation of the selected test to calculate p.value. For one-vs-one comparisons choose t.test, wilcox.test, "chisq.test", "cor.test" or lmFit (=limma), for one-vs-all or all-vs-all comparison choose aov (=anova), welch(=welch anova), kruskal.test or lmFit (=limma) \strong{Default = "lmFit"}
#' @param StatPadj \emph{Optional: } String which contains an abbreviation of the selected p.adjusted test for p.value correction for multiple Hypothesis testing. Search: ?p.adjust for more methods:"BH", "fdr", "bonferroni", "holm", etc.\strong{Default = "fdr"}
#' @param SettingsFile_Metab \emph{Optional: } DF which contains the metadata information , i.e. pathway information, retention time,..., for each metabolite. The row names must match the metabolite names in the columns of the InputData. \strong{Default = NULL}
#' @param CoRe \emph{Optional: } TRUE or FALSE for whether a Consumption/Release input is used. \strong{Default = FALSE}
#' @param VST TRUE or FALSE for whether to use variance stabilizing transformation on the data when linear modeling is used for hypothesis testing. \strong{Default = FALSE}
#' @param PerformShapiro TRUE or FALSE for whether to perform the shapiro.test and get informed about data distribution (normal versus not-normal distribution. \strong{Default = TRUE}
#' @param PerformBartlett TRUE or FALSE for whether to perform the bartlett.test. \strong{Default = TRUE}
#' @param Transform TRUE or FALSE. If TRUE we expect the data to be not log2 transformed and log2 transformation will be performed within the limma function and Log2FC calculation. If FALSE we expect the data to be log2 transformed as this impacts the Log2FC calculation and limma. \strong{Default= TRUE}
#' @param SaveAs_Plot \emph{Optional: } Select the file type of output plots. Options are svg, png, pdf. \strong{Default = svg}
#' @param SaveAs_Table \emph{Optional: } File types for the analysis results are: "csv", "xlsx", "txt". \strong{Default = "csv"}
#' @param PrintPlot \emph{Optional: } TRUE or FALSE, if TRUE Volcano plot is saved as an overview of the results. \strong{Default = TRUE}
#' @param FolderPath \emph{Optional:} Path to the folder the results should be saved at. \strong{Default = NULL}
#'
#' @return Dependent on parameter settings, list of lists will be returned for DMA (DF of each comparison), Shapiro (Includes DF and Plot), Bartlett (Includes DF and Histogram), VST (Includes DF and Plot) and VolcanoPlot (Plots of each comparison).
#'
#' @examples
#' Intra <- MetaProViz::ToyData("IntraCells_Raw")[-c(49:58) ,]
#' ResI <- MetaProViz::DMA(InputData=Intra[ ,-c(1:3)],
#' SettingsFile_Sample=Intra[ , c(1:3)],
#' SettingsInfo = c(Conditions = "Conditions", Numerator = NULL, Denominator = "HK2"))
#'
#' @keywords Differential Metabolite Analysis, Multiple Hypothesis testing, Normality testing
#'
#' @importFrom dplyr rename full_join
#' @importFrom magrittr %>%
#' @importFrom tibble rownames_to_column column_to_rownames
#' @importFrom purrr map reduce
#' @importFrom logger log_info
#'
#' @export
#'
DMA <-function(InputData,
SettingsFile_Sample,
SettingsInfo = c(Conditions="Conditions", Numerator = NULL, Denominator = NULL),
StatPval ="lmFit",
StatPadj="fdr",
SettingsFile_Metab = NULL,
CoRe=FALSE,
VST = FALSE,
PerformShapiro =TRUE,
PerformBartlett =TRUE,
Transform=TRUE,
SaveAs_Plot = "svg",
SaveAs_Table = "csv",
PrintPlot = TRUE,
FolderPath = NULL
){
## ------------ Create log file ----------- ##
MetaProViz_Init()
logger::log_info("DMA: Differential metabolite analysis.")
## ------------ Check Input files ----------- ##
# HelperFunction `CheckInput`
CheckInput(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsFile_Metab=SettingsFile_Metab,
SettingsInfo=SettingsInfo,
SaveAs_Plot=SaveAs_Plot,
SaveAs_Table=SaveAs_Table,
CoRe=CoRe,
PrintPlot= PrintPlot)
# HelperFunction `CheckInput` Specific
Settings <- CheckInput_DMA(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsInfo=SettingsInfo,
StatPval=StatPval,
StatPadj=StatPadj,
PerformShapiro=PerformShapiro,
PerformBartlett=PerformBartlett,
VST=VST,
Transform=Transform)
## ------------ Create Results output folder ----------- ##
if(is.null(SaveAs_Plot)==FALSE |is.null(SaveAs_Table)==FALSE){
Folder <- SavePath(FolderName= "DMA",
FolderPath=FolderPath)
if(PerformShapiro==TRUE){
SubFolder_S <- file.path(Folder, "Shapiro")
if (!dir.exists(SubFolder_S)) {dir.create(SubFolder_S)}
}
if(PerformBartlett==TRUE){
SubFolder_B <- file.path(Folder, "Bartlett")
if (!dir.exists(SubFolder_B)) {dir.create(SubFolder_B)}
}
if(VST==TRUE){
SubFolder_V <- file.path(Folder, "VST")
if (!dir.exists(SubFolder_V)) {dir.create(SubFolder_V)}
}
}
###############################################################################################################################################################################################################
## ------------ Check hypothesis test assumptions ----------- ##
# 1. Normality
if(PerformShapiro==TRUE){
if(length(Settings[["Metabolites_Miss"]]>=1)){
message("There are NA's/0s in the data. This can impact the output of the SHapiro-Wilk test for all metabolites that include NAs/0s.")#
}
tryCatch(
{
Shapiro_output <-suppressWarnings(Shapiro(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsInfo=SettingsInfo,
StatPval=StatPval,
QQplots=FALSE))
},
error = function(e) {
message("Error occurred during Shapiro that performs the Shapiro-Wilk test. Message: ", conditionMessage(e))
}
)
}
# 2. Variance homogeneity
if(PerformBartlett==TRUE){
if(Settings[["MultipleComparison"]]==TRUE){#if we only have two conditions, which can happen even tough multiple comparison (C1 versus C2 and C2 versus C1 is done)
UniqueConditions <- SettingsFile_Sample%>%
subset(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]] %in% Settings[["numerator"]] | SettingsFile_Sample[[SettingsInfo[["Conditions"]]]] %in% Settings[["denominator"]], select = c(SettingsInfo[["Conditions"]]))
UniqueConditions <- unique(UniqueConditions[[SettingsInfo[["Conditions"]]]])
if(length(UniqueConditions)>2){
tryCatch(
{
Bartlett_output<-suppressWarnings(Bartlett(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsInfo=SettingsInfo))
},
error = function(e) {
message("Error occurred during Bartlett that performs the Bartlett test. Message: ", conditionMessage(e))
}
)
}
}
}
###############################################################################################################################################################################################################
#### Prepare the data ######
#1. Metabolite names:
savedMetaboliteNames <- data.frame("InputName"=colnames(InputData))
savedMetaboliteNames$Metabolite <- paste0("M", seq(1,length(colnames(InputData))))
colnames(InputData) <- savedMetaboliteNames$Metabolite
################################################################################################################################################################################################
############### Calculate Log2FC, pval, padj, tval and add additional info ###############
Log2FC_table <- Log2FC_fun(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsInfo=SettingsInfo,
CoRe=CoRe,
Transform=Transform)
################################################################################################################################################################################################
############### Perform Hypothesis testing ###############
if(Settings[["MultipleComparison"]] == FALSE){
if(StatPval=="lmFit"){
STAT_C1vC2 <- DMA_Stat_limma(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsInfo=SettingsInfo,
StatPadj=StatPadj,
Log2FC_table=Log2FC_table,
CoRe=CoRe,
Transform=Transform)
}else{
STAT_C1vC2 <-DMA_Stat_single(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsInfo=SettingsInfo,
Log2FC_table=Log2FC_table,
StatPval=StatPval,
StatPadj=StatPadj)
}
}else{ # MultipleComparison = TRUE
#Correct data heteroscedasticity
if(StatPval!="lmFit" & VST == TRUE){
VST_res <- vst(InputData)
InputData <- VST_res[["DFs"]][["Corrected_data"]]
}
if(Settings[["all_vs_all"]] ==TRUE){
message("No conditions were specified as numerator or denumerator. Performing multiple testing `all-vs-all` using ", paste(StatPval), ".")
}else{# for 1 vs all
message("No condition was specified as numerator and ", Settings[["denominator"]], " was selected as a denominator. Performing multiple testing `all-vs-one` using ", paste(StatPval), ".")
}
if(StatPval=="aov"){
STAT_C1vC2 <- AOV(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsInfo=SettingsInfo,
Log2FC_table=Log2FC_table)
}else if(StatPval=="kruskal.test"){
STAT_C1vC2 <-Kruskal(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsInfo=SettingsInfo,
Log2FC_table=Log2FC_table,
StatPadj=StatPadj)
}else if(StatPval=="welch"){
STAT_C1vC2 <-Welch(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsInfo=SettingsInfo,
Log2FC_table=Log2FC_table)
}else if(StatPval=="lmFit"){
STAT_C1vC2 <- DMA_Stat_limma(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsInfo=SettingsInfo,
StatPadj=StatPadj,
Log2FC_table=Log2FC_table,
CoRe=CoRe,
Transform=Transform)
}
}
################################################################################################################################################################################################
############### Add the previous metabolite names back ###############
DMA_Output <- lapply(STAT_C1vC2, function(df){
merged_df <- merge(savedMetaboliteNames, df, by = "Metabolite", all.y = TRUE)
merged_df <-merged_df[,-1]%>%#remove the names we used as part of the function and add back the input names.
dplyr::rename("Metabolite"=1)
return(merged_df)
})
################################################################################################################################################################################################
############### Add the metabolite Metadata if available ###############
if(is.null(SettingsFile_Metab) == FALSE){
DMA_Output <- lapply(DMA_Output, function(df){
merged_df <- merge(df,SettingsFile_Metab%>%tibble::rownames_to_column("Metabolite") , by = "Metabolite", all.x = TRUE)
return(merged_df)
})
}
################################################################################################################################################################################################
############### For CoRe=TRUE create summary of Feature_metadata ###############
if(CoRe==TRUE){
df_list_selected <- purrr::map(names(DMA_Output), function(df_name) {
df <- DMA_Output[[df_name]] # Extract the dataframe
# Extract the dynamic column name
core_col <- grep("^CoRe_", names(df), value = TRUE) # Find the column that starts with "CoRe_"
# Filter only columns where the part after "CoRe_" is in valid_conditions
core_col <- core_col[str_remove(core_col, "^CoRe_") %in% unique(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]])]
# Select only the relevant columns
df_selected <- df %>%
select(Metabolite, all_of(core_col))
return(df_selected)
})
# Merge all dataframes by "Metabolite"
merged_df <- purrr::reduce(df_list_selected, dplyr::full_join, by = "Metabolite")
names(merged_df) <- gsub("\\.x$", "", names(merged_df))#It is likely we have duplications that cause .x, .y, .x.x, .y.y, etc. to be added to the column names. We only keep one column (.x)
Feature_Metadata <- merged_df %>%
select(-all_of(grep("\\.[xy]+$", names(merged_df), value = TRUE)))#Now we remove all other columns with .x.x, .y.y, etc.
if(is.null(SettingsFile_Metab) == FALSE){ #Add to Metadata file:
Feature_Metadata <- merge(SettingsFile_Metab%>%tibble::rownames_to_column("Metabolite"), Feature_Metadata , by = "Metabolite", all.x = TRUE)
}
}
################################################################################################################################################################################################
############### Plots ###############
if(CoRe==TRUE){
x <- "Log2(Distance)"
VolPlot_SettingsInfo= c(color="CoRe")
VolPlot_SettingsFile = DMA_Output
}else{
x <- "Log2FC"
VolPlot_SettingsInfo= NULL
VolPlot_SettingsFile = NULL
}
volplotList = list()
for(DF in names(DMA_Output)){ # DF = names(DMA_Output)[2]
Volplotdata<- DMA_Output[[DF]]
if(CoRe==TRUE){
VolPlot_SettingsFile <- DMA_Output[[DF]]%>%tibble::column_to_rownames("Metabolite")
}
dev.new()
VolcanoPlot <- invisible(VizVolcano(PlotSettings="Standard",
InputData=Volplotdata%>%tibble::column_to_rownames("Metabolite"),
SettingsInfo=VolPlot_SettingsInfo,
SettingsFile_Metab=VolPlot_SettingsFile,
y= "p.adj",
x= x,
PlotName= DF,
Subtitle= bquote(italic("Differential Metabolite Analysis")),
SaveAs_Plot= NULL))
DF_save <- gsub("[^A-Za-z0-9._-]", "_", DF)## Remove special characters and replace spaces with underscores
volplotList[[DF_save]]<- VolcanoPlot[["Plot_Sized"]][[1]]
dev.off()
}
######################################################################################################################################################################
##----- Save and Return
DMA_Output_List <- list()
#Here we make a list in which we will save the outputs:
if(PerformShapiro==TRUE & exists("Shapiro_output")==TRUE){
suppressMessages(suppressWarnings(
SaveRes(InputList_DF=Shapiro_output[["DF"]],
InputList_Plot= Shapiro_output[["Plot"]][["Distributions"]],
SaveAs_Table=SaveAs_Table,
SaveAs_Plot=SaveAs_Plot,
FolderPath= SubFolder_S ,
FileName= "ShapiroTest",
CoRe=CoRe,
PrintPlot=PrintPlot)))
DMA_Output_List <- list("ShapiroTest"=Shapiro_output)
}
if(PerformBartlett==TRUE & exists("Bartlett_output")==TRUE){
suppressMessages(suppressWarnings(
SaveRes(InputList_DF=Bartlett_output[["DF"]],
InputList_Plot= Bartlett_output[["Plot"]],
SaveAs_Table=SaveAs_Table,
SaveAs_Plot=SaveAs_Plot,
FolderPath= SubFolder_B ,
FileName= "BartlettTest",
CoRe=CoRe,
PrintPlot=PrintPlot)))
DMA_Output_List <- c(DMA_Output_List, list("BartlettTest"=Bartlett_output))
}
if(VST==TRUE & exists("VST_res")==TRUE){
suppressMessages(suppressWarnings(
SaveRes(InputList_DF=VST_res[["DF"]],
InputList_Plot= VST_res[["Plot"]],
SaveAs_Table=SaveAs_Table,
SaveAs_Plot=SaveAs_Plot,
FolderPath= SubFolder_V ,
FileName= "VST_res",
CoRe=CoRe,
PrintPlot=PrintPlot)))
DMA_Output_List <- c(DMA_Output_List, list("VSTres"=Bartlett_output))
}
if(CoRe==TRUE){
suppressMessages(suppressWarnings(
SaveRes(InputList_DF=list("Feature_Metadata"=Feature_Metadata),
InputList_Plot= NULL,
SaveAs_Table=SaveAs_Table,
SaveAs_Plot=NULL,
FolderPath= Folder,
FileName= "DMA",
CoRe=CoRe,
PrintPlot=PrintPlot)))
DMA_Output_List <- c(DMA_Output_List, list("Feature_Metadata"=Feature_Metadata))
}
suppressMessages(suppressWarnings(
SaveRes(InputList_DF=DMA_Output,#This needs to be a list, also for single comparisons
InputList_Plot= volplotList,
SaveAs_Table=SaveAs_Table,
SaveAs_Plot=SaveAs_Plot,
FolderPath= Folder,
FileName= "DMA",
CoRe=CoRe,
PrintPlot=PrintPlot)))
DMA_Output_List <- c(DMA_Output_List, list("DMA"=DMA_Output, "VolcanoPlot"=volplotList))
return(invisible(DMA_Output_List))
}
###############################
### ### ### Log2FC ### ### ###
###############################
#' This helper function calculates the Log2(FoldChange) or in case of CoRe Log2(Distance).
#'
#' @param InputData DF with unique sample identifiers as row names and metabolite numerical values in columns with metabolite identifiers as column names. Use NA for metabolites that were not detected.
#' @param SettingsFile_Sample DF which contains metadata information about the samples, which will be combined with your input data based on the unique sample identifiers used as rownames.
#' @param SettingsInfo \emph{Optional: } Named vector including the information about the conditions column information on numerator or denominator c(Conditions="ColumnName_SettingsFile", Numerator = "ColumnName_SettingsFile", Denominator = "ColumnName_SettingsFile"). Denominator and Numerator will specify which comparison(s) will be done (one-vs-one, all-vs-one, all-vs-all), e.g. Denominator=NULL and Numerator =NULL selects all the condition and performs multiple comparison all-vs-all. Log2FC are obtained by dividing the numerator by the denominator, thus positive Log2FC values mean higher expression in the numerator. \strong{Default = c(conditions="Conditions", numerator = NULL, denumerator = NULL)}
#' @param CoRe \emph{Optional: } TRUE or FALSE for whether a Consumption/Release input is used \strong{default = FALSE}
#' @param Transform \emph{Optional: } If TRUE we expect the data to be not log2 transformed and log2 transformation will be performed within the limma function and Log2FC calculation. If FALSE we expect the data to be log2 transformed as this impacts the Log2FC calculation and limma.\strong{default = TRUE}
#'
#' @return List of DFs named after comparison (e.g. Tumour versus Normal) with Log2FC or Log2(Distance) column and column with feature names
#'
#' @keywords Log2FC, CoRe, Distance
#'
#' @importFrom dplyr select_if filter rename mutate summarise_all
#' @importFrom magrittr %>%
#' @importFrom gtools foldchange2logratio
#' @importFrom tibble rownames_to_column
#'
#' @noRd
#'
Log2FC_fun <-function(InputData,
SettingsFile_Sample,
SettingsInfo=c(Conditions="Conditions", Numerator = NULL, Denominator = NULL),
CoRe=FALSE,
Transform=TRUE
){
## ------------ Create log file ----------- ##
MetaProViz_Init()
# ------------ Assignments ----------- ##
if("Denominator" %in% names(SettingsInfo)==FALSE & "Numerator" %in% names(SettingsInfo) ==FALSE){
# all-vs-all: Generate all pairwise combinations
conditions = SettingsFile_Sample[[SettingsInfo[["Conditions"]]]]
denominator <-unique(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]])
numerator <-unique(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]])
comparisons <- combn(unique(conditions), 2) %>% as.matrix()
#Settings:
MultipleComparison = TRUE
all_vs_all = TRUE
}else if("Denominator" %in% names(SettingsInfo)==TRUE & "Numerator" %in% names(SettingsInfo)==FALSE){
#all-vs-one: Generate the pairwise combinations
conditions = SettingsFile_Sample[[SettingsInfo[["Conditions"]]]]
denominator <- SettingsInfo[["Denominator"]]
numerator <-unique(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]])
# Remove denom from num
numerator <- numerator[!numerator %in% denominator]
comparisons <- t(expand.grid(numerator, denominator)) %>% as.data.frame()
#Settings:
MultipleComparison = TRUE
all_vs_all = FALSE
}else if("Denominator" %in% names(SettingsInfo)==TRUE & "Numerator" %in% names(SettingsInfo)==TRUE){
# one-vs-one: Generate the comparisons
denominator <- SettingsInfo[["Denominator"]]
numerator <- SettingsInfo[["Numerator"]]
comparisons <- matrix(c(numerator, denominator))
#Settings:
MultipleComparison = FALSE
all_vs_all = FALSE
}
## ------------ Check Missingness ------------- ##
Num <- InputData %>%#Are sample numbers enough?
filter(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]] %in% numerator) %>%
dplyr::select_if(is.numeric)#only keep numeric columns with metabolite values
Denom <- InputData %>%
dplyr::filter(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]] %in% denominator) %>%
dplyr::select_if(is.numeric)
Num_Miss <- replace(Num, Num==0, NA)
Num_Miss <- Num_Miss[, (colSums(is.na(Num_Miss)) > 0), drop = FALSE]
Denom_Miss <- replace(Denom, Denom==0, NA)
Denom_Miss <- Denom_Miss[, (colSums(is.na(Denom_Miss)) > 0), drop = FALSE]
if((ncol(Num_Miss)>0 & ncol(Denom_Miss)==0)){
Metabolites_Miss <- colnames(Num_Miss)
}else if(ncol(Num_Miss)==0 & ncol(Denom_Miss)>0){
Metabolites_Miss <- colnames(Denom_Miss)
}else if(ncol(Num_Miss)>0 & ncol(Denom_Miss)>0){
Metabolites_Miss <- c(colnames(Num_Miss), colnames(Denom_Miss))
Metabolites_Miss <- unique(Metabolites_Miss)
}else{
Metabolites_Miss <- c(colnames(Num_Miss), colnames(Denom_Miss))
Metabolites_Miss <- unique(Metabolites_Miss)
}
## ------------ Denominator/numerator ----------- ##
# Denominator and numerator: Define if we compare one_vs_one, one_vs_all or all_vs_all.
if("Denominator" %in% names(SettingsInfo)==FALSE & "Numerator" %in% names(SettingsInfo) ==FALSE){
MultipleComparison = TRUE
}else if("Denominator" %in% names(SettingsInfo)==TRUE & "Numerator" %in% names(SettingsInfo)==FALSE){
MultipleComparison = TRUE
}else if("Denominator" %in% names(SettingsInfo)==TRUE & "Numerator" %in% names(SettingsInfo)==TRUE){
MultipleComparison = FALSE
}
####################################################################################################################################
## ----------------- Log2FC ----------------------------
Log2FC_table <- list()# Create an empty list to store results data frames
for(column in 1:dim(comparisons)[2]){
C1 <- InputData %>% # Numerator
dplyr::filter(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]] %in% comparisons[1,column]) %>%
dplyr::select_if(is.numeric)#only keep numeric columns with metabolite values
C2 <- InputData %>% # Deniminator
dplyr::filter(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]] %in% comparisons[2,column]) %>%
dplyr::select_if(is.numeric)
## ------------ Calculate Log2FC ----------- ##
# For C1_Mean and C2_Mean use 0 to obtain values, leading to Log2FC=NA if mean = 0 (If one value is NA, the mean will be NA even though all other values are available.)
C1_Zero <- C1
C1_Zero[is.na(C1_Zero)] <- 0
Mean_C1 <- C1_Zero %>%
dplyr::summarise_all("mean")
C2_Zero <- C2
C2_Zero[is.na(C2_Zero)] <- 0
Mean_C2 <- C2_Zero %>%
dplyr::summarise_all("mean")
if(CoRe==TRUE){#Calculate absolute distance between the means. log2 transform and add sign (-/+):
#CoRe values can be negative and positive, which can does not allow us to calculate a Log2FC.
Mean_C1_t <- as.data.frame(t(Mean_C1))%>%
tibble::rownames_to_column("Metabolite")
Mean_C2_t <- as.data.frame(t(Mean_C2))%>%
tibble::rownames_to_column("Metabolite")
Mean_Merge <-merge(Mean_C1_t, Mean_C2_t, by="Metabolite", all=TRUE)%>%
dplyr::rename("C1"=2,
"C2"=3)
#Deal with NA/0s
Mean_Merge$`NA/0` <- Mean_Merge$Metabolite %in% Metabolites_Miss#Column to enable the check if mean values of 0 are due to missing values (NA/0) and not by coincidence
if(any((Mean_Merge$`NA/0`==FALSE & Mean_Merge$C1 ==0) | (Mean_Merge$`NA/0`==FALSE & Mean_Merge$C2==0))==TRUE){
Mean_Merge <- Mean_Merge%>%
dplyr::mutate(C1 = case_when(C2 == 0 & `NA/0`== TRUE ~ paste(C1),#Here we have a "true" 0 value due to 0/NAs in the input data
C1 == 0 & `NA/0`== TRUE ~ paste(C1),#Here we have a "true" 0 value due to 0/NAs in the input data
C2 == 0 & `NA/0`== FALSE ~ paste(C1+1),#Here we have a "false" 0 value that occured at random and not due to 0/NAs in the input data, hence we add the constant +1
C1 == 0 & `NA/0`== FALSE ~ paste(C1+1),#Here we have a "false" 0 value that occured at random and not due to 0/NAs in the input data, hence we add the constant +1
TRUE ~ paste(C1)))%>%
dplyr::mutate(C2 = case_when(C1 == 0 & `NA/0`== TRUE ~ paste(C2),#Here we have a "true" 0 value due to 0/NAs in the input data
C2 == 0 & `NA/0`== TRUE ~ paste(C2),#Here we have a "true" 0 value due to 0/NAs in the input data
C1 == 0 & `NA/0`== FALSE ~ paste(C2+1),#Here we have a "false" 0 value that occured at random and not due to 0/NAs in the input data, hence we add the constant +1
C2 == 0 & `NA/0`== FALSE ~ paste(C2+1),#Here we have a "false" 0 value that occured at random and not due to 0/NAs in the input data, hence we add the constant +1
TRUE ~ paste(C2)))%>%
dplyr::mutate(C1 = as.numeric(C1))%>%
dplyr::mutate(C2 = as.numeric(C2))
X <- Mean_Merge%>%
subset((Mean_Merge$`NA/0`==FALSE & Mean_Merge$C1 ==0) | (Mean_Merge$`NA/0`==FALSE & Mean_Merge$C2==0))
message("We added +1 to the mean value of metabolite(s) ", paste0(X$Metabolite, collapse = ", "), ", since the mean of the replicate values where 0. This was not due to missing values (NA/0).")
}
#Add the distance column:
Mean_Merge$`Log2(Distance)` <-log2(abs(Mean_Merge$C1 - Mean_Merge$C2))
Mean_Merge <- Mean_Merge%>%#Now we can adapt the values to take into account the distance
dplyr::mutate(`Log2(Distance)` = case_when(C1 > C2 ~ paste(`Log2(Distance)`*+1),#If C1>C2 the distance stays positive to reflect that C1 > C2
C1 < C2 ~ paste(`Log2(Distance)`*-1),#If C1<C2 the distance gets a negative sign to reflect that C1 < C2
TRUE ~ 'NA'))%>%
dplyr::mutate(`Log2(Distance)` = as.numeric(`Log2(Distance)`))
#Add additional information:
temp1 <- Mean_C1
temp2 <- Mean_C2
#Add Info of CoRe:
CoRe_info <- rbind(temp1, temp2,rep(0,length(temp1)))
for (i in 1:length(temp1)){
if (temp1[i]>0 & temp2[i]>0){
CoRe_info[3,i] <- "Released"
}else if (temp1[i]<0 & temp2[i]<0){
CoRe_info[3,i] <- "Consumed"
}else if(temp1[i]>0 & temp2[i]<0){
CoRe_info[3,i] <- paste("Released in" ,comparisons[1,column] , "and Consumed",comparisons[2,column] , sep=" ")
} else if(temp1[i]<0 & temp2[i]>0){
CoRe_info[3,i] <- paste("Consumed in" ,comparisons[1,column] , " and Released",comparisons[2,column] , sep=" ")
}else{
CoRe_info[3,i] <- "No Change"
}
}
CoRe_info <- t(CoRe_info) %>% as.data.frame()
CoRe_info <- rownames_to_column(CoRe_info, "Metabolite")
names(CoRe_info)[2] <- paste("Mean", comparisons[1,column], sep="_")
names(CoRe_info)[3] <- paste("Mean", comparisons[2,column], sep="_")
names(CoRe_info)[4] <- "CoRe_specific"
CoRe_info <-CoRe_info%>%
dplyr::mutate(CoRe = case_when(CoRe_specific == "Released" ~ 'Released',
CoRe_specific == "Consumed" ~ 'Consumed',
TRUE ~ 'Released/Consumed'))%>%
dplyr::mutate(!!paste("CoRe_", comparisons[1,column], sep="") := case_when(CoRe_specific == "Released" ~ 'Released',
CoRe_specific == "Consumed" ~ 'Consumed',
CoRe_specific == paste("Consumed in" ,comparisons[1,column] , " and Released",comparisons[2,column] , sep=" ")~ 'Consumed',
CoRe_specific == paste("Released in" ,comparisons[1,column] , "and Consumed",comparisons[2,column] , sep=" ")~ 'Released',
TRUE ~ 'NA'))%>%
dplyr::mutate(!!paste("CoRe_", comparisons[2,column], sep="") := case_when(CoRe_specific == "Released" ~ 'Released',
CoRe_specific == "Consumed" ~ 'Consumed',
CoRe_specific == paste("Consumed in" ,comparisons[1,column] , " and Released",comparisons[2,column] , sep=" ")~ 'Released',
CoRe_specific == paste("Released in" ,comparisons[1,column] , "and Consumed",comparisons[2,column] , sep=" ")~ 'Consumed',
TRUE ~ 'NA'))
Log2FC_C1vC2 <-merge(Mean_Merge[,c(1,5)], CoRe_info[,c(1,2,6,3,7,4:5)], by="Metabolite", all.x=TRUE)
#Add info on Input:
temp3 <- as.data.frame(t(C1))%>%tibble::rownames_to_column("Metabolite")
temp4 <- as.data.frame(t(C2))%>%tibble::rownames_to_column("Metabolite")
temp_3a4 <- merge(temp3, temp4, by="Metabolite", all=TRUE)
Log2FC_C1vC2 <- merge(Log2FC_C1vC2, temp_3a4, by="Metabolite", all.x=TRUE)
#Return DFs
##Make reverse DF
Log2FC_C2vC1 <- Log2FC_C1vC2
Log2FC_C2vC1$`Log2(Distance)` <- Log2FC_C2vC1$`Log2(Distance)` *-1
##Name them
if(MultipleComparison == TRUE){
logname <- paste(comparisons[1,column], comparisons[2,column],sep="_vs_")
logname_reverse <- paste(comparisons[2,column], comparisons[1,column],sep="_vs_")
# Store the data frame in the results list, named after the contrast
Log2FC_table[[logname]] <- Log2FC_C1vC2
Log2FC_table[[logname_reverse]] <- Log2FC_C2vC1
}else{
Log2FC_table <- Log2FC_C1vC2
}
}else if(CoRe==FALSE){
#Mean values could be 0, which can not be used to calculate a Log2FC and hence the Log2FC(A versus B)=(log2(A+x)-log2(B+x)) for A and/or B being 0, with x being set to 1
Mean_C1_t <- as.data.frame(t(Mean_C1))%>%
tibble::rownames_to_column("Metabolite")
Mean_C2_t <- as.data.frame(t(Mean_C2))%>%
tibble::rownames_to_column("Metabolite")
Mean_Merge <- merge(Mean_C1_t, Mean_C2_t, by="Metabolite", all=TRUE)%>%
dplyr::rename("C1"=2,
"C2"=3)
Mean_Merge$`NA/0` <- Mean_Merge$Metabolite %in% Metabolites_Miss#Column to enable the check if mean values of 0 are due to missing values (NA/0) and not by coincidence
Mean_Merge <- Mean_Merge%>%
dplyr::mutate(C1_Adapted = case_when(C2 == 0 & `NA/0`== TRUE ~ paste(C1),#Here we have a "true" 0 value due to 0/NAs in the input data
C1 == 0 & `NA/0`== TRUE ~ paste(C1),#Here we have a "true" 0 value due to 0/NAs in the input data
C2 == 0 & `NA/0`== FALSE ~ paste(C1+1),#Here we have a "false" 0 value that occured at random and not due to 0/NAs in the input data, hence we add the constant +1
C1 == 0 & `NA/0`== FALSE ~ paste(C1+1),#Here we have a "false" 0 value that occured at random and not due to 0/NAs in the input data, hence we add the constant +1
TRUE ~ paste(C1)))%>%
dplyr::mutate(C2_Adapted = case_when(C1 == 0 & `NA/0`== TRUE ~ paste(C2),#Here we have a "true" 0 value due to 0/NAs in the input data
C2 == 0 & `NA/0`== TRUE ~ paste(C2),#Here we have a "true" 0 value due to 0/NAs in the input data
C1 == 0 & `NA/0`== FALSE ~ paste(C2+1),#Here we have a "false" 0 value that occured at random and not due to 0/NAs in the input data, hence we add the constant +1
C2 == 0 & `NA/0`== FALSE ~ paste(C2+1),#Here we have a "false" 0 value that occured at random and not due to 0/NAs in the input data, hence we add the constant +1
TRUE ~ paste(C2)))%>%
dplyr::mutate(C1_Adapted = as.numeric(C1_Adapted))%>%
dplyr::mutate(C2_Adapted = as.numeric(C2_Adapted))
if(any((Mean_Merge$`NA/0`==FALSE & Mean_Merge$C1 ==0) | (Mean_Merge$`NA/0`==FALSE & Mean_Merge$C2==0))==TRUE){
X <- Mean_Merge%>%
subset((Mean_Merge$`NA/0`==FALSE & Mean_Merge$C1 ==0) | (Mean_Merge$`NA/0`==FALSE & Mean_Merge$C2==0))
message("We added +1 to the mean value of metabolite(s) ", paste0(X$Metabolite, collapse = ", "), ", since the mean of the replicate values where 0. This was not due to missing values (NA/0).")
}
#Calculate the Log2FC
if(Transform== TRUE){#data are not log2 transformed
Mean_Merge$FC_C1vC2 <- Mean_Merge$C1_Adapted/Mean_Merge$C2_Adapted #FoldChange
Mean_Merge$Log2FC <- gtools::foldchange2logratio(Mean_Merge$FC_C1vC2, base=2)
}
if(Transform== FALSE){#data has been log2 transformed and hence we need to take this into account when calculating the log2FC
Mean_Merge$FC_C1vC2 <- "Empty"
Mean_Merge$Log2FC <- Mean_Merge$C1_Adapted - Mean_Merge$C2_Adapted
}
#Add info on Input:
temp3 <- as.data.frame(t(C1))%>%tibble::rownames_to_column("Metabolite")
temp4 <- as.data.frame(t(C2))%>%tibble::rownames_to_column("Metabolite")
temp_3a4 <-merge(temp3, temp4, by="Metabolite", all=TRUE)
Log2FC_C1vC2 <-merge(Mean_Merge[,c(1,8)], temp_3a4, by="Metabolite", all.x=TRUE)
#Return DFs
##Make reverse DF
Log2FC_C2vC1 <-Log2FC_C1vC2
Log2FC_C2vC1$Log2FC <- Log2FC_C2vC1$Log2FC*-1
if(MultipleComparison == TRUE){
logname <- paste(comparisons[1,column], comparisons[2,column],sep="_vs_")
logname_reverse <- paste(comparisons[2,column], comparisons[1,column],sep="_vs_")
# Store the data frame in the results list, named after the contrast
Log2FC_table[[logname]] <- Log2FC_C1vC2
Log2FC_table[[logname_reverse]] <- Log2FC_C2vC1
}else{
Log2FC_table <- Log2FC_C1vC2
}
}
}
return(invisible(Log2FC_table))
}
##########################################################################################
### ### ### DMA helper function: Internal Function to perform single comparison ### ### ###
##########################################################################################
#' This helper function to calculate One-vs-One comparison statistics
#'
#' @param InputData DF with unique sample identifiers as row names and metabolite numerical values in columns with metabolite identifiers as column names. Use NA for metabolites that were not detected.
#' @param SettingsFile_Sample DF which contains metadata information about the samples, which will be combined with your input data based on the unique sample identifiers used as rownames.
#' @param SettingsInfo Named vector including the information about the conditions column information on numerator or denominator c(Conditions="ColumnName_SettingsFile", Numerator = "ColumnName_SettingsFile", Denominator = "ColumnName_SettingsFile"). Denominator and Numerator will specify which comparison(s) will be done (here one-vs-one).
#' @param Log2FC_table \emph{Optional: } This is a List of DFs including a column "MetaboliteID" and Log2FC or Log2(Distance). This is the output from MetaProViz:::Log2FC_fun. If NULL, the output statistics will not be added into the Log2FC/Log2(Distance) DFs. \strong{Default = NULL}
#' @param StatPval \emph{Optional: } String which contains an abbreviation of the selected test to calculate p.value. For one-vs-one comparisons choose t.test, wilcox.test, "chisq.test" or "cor.test", \strong{Default = "t.test"}
#' @param StatPadj \emph{Optional: } String which contains an abbreviation of the selected p.adjusted test for p.value correction for multiple Hypothesis testing. Search: ?p.adjust for more methods:"BH", "fdr", "bonferroni", "holm", etc.\strong{Default = "fdr"}
#'
#' @return List of DFs named after comparison (e.g. tumour versus Normal) with p-value, t-value and adjusted p-value column and column with feature names
#'
#' @keywords Statistical testing, p-value, t-value
#'
#' @importFrom stats p.adjust
#' @importFrom dplyr select_if filter rename mutate summarise_all
#' @importFrom magrittr %>%
#' @importFrom tibble rownames_to_column
#'
#' @noRd
#'
DMA_Stat_single <- function(InputData,
SettingsFile_Sample,
SettingsInfo,
Log2FC_table=NULL,
StatPval="t.test",
StatPadj="fdr"){
## ------------ Create log file ----------- ##
MetaProViz_Init()
## ------------ Check Missingness ------------- ##
Num <- InputData %>%#Are sample numbers enough?
dplyr::filter(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]] %in% SettingsInfo[["Numerator"]]) %>%
dplyr::select_if(is.numeric)#only keep numeric columns with metabolite values
Denom <- InputData %>%
dplyr::filter(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]] %in% SettingsInfo[["Denominator"]]) %>%
dplyr::select_if(is.numeric)
Num_Miss <- replace(Num, Num==0, NA)
Num_Miss <- Num_Miss[, (colSums(is.na(Num_Miss)) > 0), drop = FALSE]
Denom_Miss <- replace(Denom, Denom==0, NA)
Denom_Miss <- Denom_Miss[, (colSums(is.na(Denom_Miss)) > 0), drop = FALSE]
if((ncol(Num_Miss)>0 & ncol(Denom_Miss)==0)){
Metabolites_Miss <- colnames(Num_Miss)
}else if(ncol(Num_Miss)==0 & ncol(Denom_Miss)>0){
Metabolites_Miss <- colnames(Denom_Miss)
}else if(ncol(Num_Miss)>0 & ncol(Denom_Miss)>0){
Metabolites_Miss <- c(colnames(Num_Miss), colnames(Denom_Miss))
Metabolites_Miss <- unique(Metabolites_Miss)
}else{
Metabolites_Miss <- c(colnames(Num_Miss), colnames(Denom_Miss))
Metabolites_Miss <- unique(Metabolites_Miss)
}
# Comparisons
comparisons <- matrix(c(SettingsInfo[["Numerator"]], SettingsInfo[["Denominator"]]))
## ------------ Perform Hypothesis testing ----------- ##
for(column in 1:dim(comparisons)[2]){
C1 <- InputData %>% # Numerator
dplyr::filter(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]] %in% comparisons[1,column]) %>%
dplyr::select_if(is.numeric)#only keep numeric columns with metabolite values
C2 <- InputData %>% # Denominator
dplyr::filter(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]] %in% comparisons[2,column]) %>%
dplyr::select_if(is.numeric)
}
# For C1 and C2 we use 0, since otherwise we can not perform the statistical testing.
C1[is.na(C1)] <- 0
C2[is.na(C2)] <- 0
#### 1. p.value and test statistics (=t.val)
T_C1vC2 <-mapply(StatPval, x= as.data.frame(C2), y = as.data.frame(C1), SIMPLIFY = F)
VecPVAL_C1vC2 <- c()
VecTVAL_C1vC2 <- c()
for(i in 1:length(T_C1vC2)){
p_value <- unlist(T_C1vC2[[i]][3])
t_value <- unlist(T_C1vC2[[i]])[1] # Extract the t-value
VecPVAL_C1vC2[i] <- p_value
VecTVAL_C1vC2[i] <- t_value
}
Metabolite <- colnames(C2)
PVal_C1vC2 <- data.frame(Metabolite, p.val = VecPVAL_C1vC2, t.val = VecTVAL_C1vC2)
#we set p.val= NA, for metabolites that had 1 or more replicates with NA/0 values and remove them prior to p-value adjustment
PVal_C1vC2$`NA/0` <- PVal_C1vC2$Metabolite %in% Metabolites_Miss
PVal_C1vC2 <-PVal_C1vC2%>%
dplyr::mutate(p.val = case_when(`NA/0`== TRUE ~ NA,
TRUE ~ paste(VecPVAL_C1vC2)))
PVal_C1vC2$p.val = as.numeric(as.character(PVal_C1vC2$p.val))
#### 2. p.adjusted
#Split data for p.value adjustment to exclude NA
PVal_NA <- PVal_C1vC2[is.na(PVal_C1vC2$p.val), c(1:3)]
PVal_C1vC2 <-PVal_C1vC2[!is.na(PVal_C1vC2$p.val), c(1:3)]
#perform adjustment
VecPADJ_C1vC2 <- stats::p.adjust((PVal_C1vC2[,2]),method = StatPadj, n = length((PVal_C1vC2[,2]))) #p-adjusted
Metabolite <- PVal_C1vC2[,1]
PADJ_C1vC2 <- data.frame(Metabolite, p.adj = VecPADJ_C1vC2)
STAT_C1vC2 <- merge(PVal_C1vC2,PADJ_C1vC2, by="Metabolite")
#Add Metabolites that have p.val=NA back into the DF for completeness.
if(nrow(PVal_NA)>0){
PVal_NA$p.adj <- NA
STAT_C1vC2 <- rbind(STAT_C1vC2, PVal_NA)
}
#Add Log2FC
if(is.null(Log2FC_table)==FALSE){
STAT_C1vC2 <- merge(Log2FC_table,STAT_C1vC2[,c(1:2,4,3)], by="Metabolite")
}
#order for t.value
STAT_C1vC2 <- STAT_C1vC2[order(STAT_C1vC2$t.val,decreasing=TRUE),] # order the df based on the t-value
#list
results_list <- list()
results_list[[paste(SettingsInfo[["Numerator"]], "_vs_", SettingsInfo[["Denominator"]])]] <- STAT_C1vC2
return(invisible(results_list))
}
################################################################
### ### ### AOV: Internal Function to perform Anova ### ### ###
################################################################
#' This helper function to calculate One-vs-All or All-vs-All comparison statistics
#'
#' @param InputData DF with unique sample identifiers as row names and metabolite numerical values in columns with metabolite identifiers as column names. Use NA for metabolites that were not detected.
#' @param SettingsFile_Sample DF which contains metadata information about the samples, which will be combined with your input data based on the unique sample identifiers used as rownames.
#' @param SettingsInfo \emph{Optional: } Named vector including the information about the conditions column information on numerator or denominator c(Conditions="ColumnName_SettingsFile", Numerator = "ColumnName_SettingsFile", Denominator = "ColumnName_SettingsFile"). Denominator and Numerator will specify which comparison(s) will be done (Here all-vs-one, all-vs-all), e.g. Denominator=NULL and Numerator =NULL selects all the condition and performs multiple comparison all-vs-all. \strong{Default = c(conditions="Conditions", numerator = NULL, denumerator = NULL)}
#' @param Log2FC_table \emph{Optional: } This is a List of DFs including a column "MetaboliteID" and Log2FC or Log2(Distance). This is the output from MetaProViz:::Log2FC_fun. If NULL, the output statistics will not be added into the Log2FC/Log2(Distance) DFs. \strong{Default = NULL}
#'
#' @return List of DFs named after comparison (e.g. tumour versus Normal) with p-value, t-value and adjusted p-value column and column with feature names
#'
#' @keywords Statistical testing, p-value, t-value
#'
#' @importFrom stats aov TukeyHSD
#' @importFrom dplyr rename
#' @importFrom magrittr %>%
#' @importFrom tibble rownames_to_column
#'
#' @noRd
#'
AOV <-function(InputData,
SettingsFile_Sample,
SettingsInfo=c(Conditions="Conditions", Numerator = NULL, Denominator = NULL),
Log2FC_table=NULL){
## ------------ Create log file ----------- ##
MetaProViz_Init()
## ------------ Denominator/numerator ----------- ##
# Denominator and numerator: Define if we compare one_vs_one, one_vs_all or all_vs_all.
if("Denominator" %in% names(SettingsInfo)==FALSE & "Numerator" %in% names(SettingsInfo) ==FALSE){
# all-vs-all: Generate all pairwise combinations
conditions = SettingsFile_Sample[[SettingsInfo[["Conditions"]]]]
denominator <-unique(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]])
numerator <-unique(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]])
comparisons <- combn(unique(conditions), 2) %>% as.matrix()
#Settings:
MultipleComparison = TRUE
all_vs_all = TRUE
}else if("Denominator" %in% names(SettingsInfo)==TRUE & "Numerator" %in% names(SettingsInfo)==FALSE){
#all-vs-one: Generate the pairwise combinations
conditions = SettingsFile_Sample[[SettingsInfo[["Conditions"]]]]
denominator <- SettingsInfo[["Denominator"]]
numerator <-unique(SettingsFile_Sample[[SettingsInfo[["Conditions"]]]])
# Remove denom from num
numerator <- numerator[!numerator %in% denominator]
comparisons <- t(expand.grid(numerator, denominator)) %>% as.data.frame()
#Settings:
MultipleComparison = TRUE
all_vs_all = FALSE
}
#############################################################################################
## 1. Anova p.val
aov.res= apply(InputData,2,function(x) stats::aov(x~conditions))
## 2. Tukey test p.adj
posthoc.res = lapply(aov.res, stats::TukeyHSD, conf.level=0.95)
Tukey_res <- do.call('rbind', lapply(posthoc.res, function(x) x[1][[1]][,'p adj'])) %>% as.data.frame()
comps <- paste(comparisons[1, ], comparisons[2, ], sep="-")# normal
opp_comps <- paste(comparisons[2, ], comparisons[1, ], sep="-")
if(sum(opp_comps %in% colnames(Tukey_res))>0){# if opposite comparisons is true
for (comp in 1: length(opp_comps)){
colnames(Tukey_res)[colnames(Tukey_res) %in% opp_comps[comp]] <- comps[comp]
}
}
## 3. t.val
Tukey_res_diff <- do.call('rbind', lapply(posthoc.res, function(x) x[1][[1]][,'diff'])) %>% as.data.frame()
if (sum(opp_comps %in% colnames(Tukey_res_diff))>0){# if oposite comparisons is true
for (comp in 1: length(opp_comps)){
colnames(Tukey_res_diff)[colnames(Tukey_res_diff) %in% opp_comps[comp]] <- comps[comp]
}
}
#Make output DFs:
Pval_table <- Tukey_res
Pval_table <- tibble::rownames_to_column(Pval_table,"Metabolite")
Tval_table <- tibble::rownames_to_column(Tukey_res_diff,"Metabolite")
common_col_names <- setdiff(names(Tukey_res_diff), "row.names")#Here we need to adapt for one_vs_all or all_vs_all
results_list <- list()
for(col_name in common_col_names){
# Create a new data frame by merging the two data frames
merged_df <- merge(Pval_table[,c("Metabolite",col_name)], Tval_table[,c("Metabolite",col_name)], by="Metabolite", all=TRUE)%>%
dplyr::rename("p.adj"=2,
"t.val"=3)
#We need to add _vs_ into the comparison col_name
pattern <- paste(conditions, collapse = "|")
conditions_present <- unique(unlist(regmatches(col_name, gregexpr(pattern, col_name))))
modified_col_name <- paste(conditions_present[1], "vs", conditions_present[2], sep = "_")
# Add the new data frame to the list with the column name as the list element name
results_list[[modified_col_name]] <- merged_df
}
# Merge the data frames in list1 and list2 based on the "Metabolite" column
if(is.null(Log2FC_table)==FALSE){
list_names <- names(results_list)
merged_list <- list()
for(name in list_names){
# Check if the data frames exist in both lists
if(name %in% names(results_list) && name %in% names(Log2FC_table)){
merged_df <- merge(results_list[[name]], Log2FC_table[[name]], by = "Metabolite", all = TRUE)
merged_df <- merged_df[,c(1,4,2:3,5:ncol(merged_df))]#reorder the columns
merged_list[[name]] <- merged_df
}
}
}else{
merged_list <- results_list
}
# Make sure the right comparisons are returned:
if(all_vs_all==TRUE){
STAT_C1vC2 <- merged_list
}else if(all_vs_all==FALSE){
#remove the comparisons that are not needed:
modified_df_list <- list()
for(df_name in names(merged_list)){
if(endsWith(df_name, SettingsInfo[["Denominator"]])){
modified_df_list[[df_name]] <- merged_list[[df_name]]
}
}
STAT_C1vC2 <- modified_df_list
}
return(invisible(STAT_C1vC2))
}
###########################################################################
### ### ### Kruskal: Internal Function to perform Kruskal test ### ### ###
###########################################################################
#' This helper function to calculate One-vs-All or All-vs-All comparison statistics
#'
#' @param InputData DF with unique sample identifiers as row names and metabolite numerical values in columns with metabolite identifiers as column names. Use NA for metabolites that were not detected.
#' @param SettingsFile_Sample DF which contains metadata information about the samples, which will be combined with your input data based on the unique sample identifiers used as rownames.
#' @param SettingsInfo \emph{Optional: } Named vector including the information about the conditions column information on numerator or denominator c(Conditions="ColumnName_SettingsFile", Numerator = "ColumnName_SettingsFile", Denominator = "ColumnName_SettingsFile"). Denominator and Numerator will specify which comparison(s) will be done (Here all-vs-one, all-vs-all), e.g. Denominator=NULL and Numerator =NULL selects all the condition and performs multiple comparison all-vs-all. \strong{Default = c(conditions="Conditions", numerator = NULL, denumerator = NULL)}
#' @param Log2FC_table \emph{Optional: } This is a List of DFs including a column "MetaboliteID" and Log2FC or Log2(Distance). This is the output from MetaProViz:::Log2FC_fun. If NULL, the output statistics will not be added into the Log2FC/Log2(Distance) DFs. \strong{Default = NULL}
#' @param StatPadj \emph{Optional: } String which contains an abbreviation of the selected p.adjusted test for p.value correction for multiple Hypothesis testing. Search: ?p.adjust for more methods:"BH", "fdr", "bonferroni", "holm", etc.\strong{Default = "fdr"}
#'
#' @return List of DFs named after comparison (e.g. tumour versus Normal) with p-value, t-value and adjusted p-value column and column with feature names
#'
#' @keywords Statistical testing, p-value, t-value
#'
#' @importFrom stats kruskal.test
#' @importFrom rstatix dunn_test
#' @importFrom dplyr rename mutate_all mutate select
#' @importFrom magrittr %>%
#' @importFrom tibble rownames_to_column column_to_rownames