-
Notifications
You must be signed in to change notification settings - Fork 1
/
mgc_exploratory_analysis_functions.R
executable file
·2877 lines (2372 loc) · 174 KB
/
mgc_exploratory_analysis_functions.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
################################
# Name: MacIntosh Cornwell
# Email: mcornwell1957@gmail.com
################################
## ISCHEMIA Subtype Analysis
## Load in Libraries
packagelist = c("NMF", "Hmisc", "tools", "caret", "blacksheepr", "mlbench", "caret", "pROC", "WGCNA", "multiROC", "scattermore", "dendextend", "devtools")
junk <- lapply(packagelist, function(xxx) suppressMessages(
require(xxx, character.only = TRUE,quietly=TRUE,warn.conflicts = FALSE)))
source_url('https://raw.githubusercontent.com/mattmuller0/Rtools/main/mgc_plotting_functions.R')
# source("/Users/tosh/Desktop/Ruggles_Lab/code/process_metadata_functions.R")
source_url('https://raw.githubusercontent.com/mattmuller0/Rtools/main/mgc_survival_functions.R')
source_url('https://raw.githubusercontent.com/mattmuller0/Rtools/main/mgc_WGCNA_functions.R')
# --------------------------------- Add on and edit the biorep table ---------------------------------
addon_and_edit_biorep_table <- function(bioreptable, addclustertypes = TRUE, ...) {
addontable1 <- data.frame(PATNUM = SOIall, CUSTOM_maxfollow = apply(bioreptable[SOIall,grepl("^T_", colnames(bioreptable))], 1, function(x) max(x)/365.25))
addontable2 <- data.frame(PATNUM = SOIall, CUSTOM_BMI_obese = ifelse(bioreptable[,"BMI"] >= 30, "Obese", "NotObese"))
addontable3 <- data.frame(PATNUM = SOIall, CUSTOM_SMOKSTAT_currentsmoker = ifelse(bioreptable[,"SMOKSTAT"] %in% "Current Smoker", "CurrentSmoker", "NotCurrentSmoker"))
addontable4 <- data.frame(PATNUM = SOIall, CUSTOM_PCIorCABG = ifelse(!is.na(bioreptable[,"FIRSTRV"]), "PCIorCABG", "NoPCIorCABG"))
# addontable5 <- data.frame(PATNUM = SOI, CUSTOM_PAD_NOCCEREB = bioreptable[,"PRCERPAD"] - bioreptable[,"PRICEREB"])
addontable6 <- data.frame(PATNUM = SOIall, CUSTOM_RACE_AGGR = ifelse(bioreptable[,"RACE"] %in% c("White", "Black or African American", "Asian"), bioreptable[,"RACE"], "Other or multiple ethnic groups"))
addontable7 <- data.frame(PATNUM = SOIall, CUSTOM_LVEFCONT_LVEFund55 = ifelse(bioreptable[,"LVEFCONT"] < 55, "LVEFund55", "NoLVEFund55"))
addontable8 <- data.frame(PATNUM = SOIall, CUSTOM_EGFR_EGFRund60 = ifelse(bioreptable[,"EGFR"] < 60, "EGFRund60", "NoEGFRund60"))
addontable9 <- data.frame(PATNUM = SOIall, CUSTOM_LDLC_LDLCund70 = ifelse(bioreptable[,"LDLC"] < 70, "LDLCund70", "NoLDLCund70"))
addontable9_2 <- data.frame(PATNUM = SOIall, CUSTOM_LDLC_LDLCund100 = ifelse(bioreptable[,"LDLC"] < 100, "LDLCund100", "NoLDLCund100"))
addontable10 <- data.frame(PATNUM = SOIall, CUSTOM_RVBPSYS_RVBPSYSund140 = ifelse(bioreptable[,"RVBPSYS"] < 140, "RVBPSYSund140", "NoRVBPSYSund140"))
addontable11 <- data.frame(PATNUM = SOIall, CUSTOM_LDLCund70andMESTATIN = ifelse(bioreptable[,"LDLC"] < 70 & bioreptable[,"MESTATIN"] == "Yes", "LDLCund70andMESTATIN", "NoLDLCund70andMESTATIN"))
addontable12 <- data.frame(PATNUM = SOIall, CUSTOM_CKD_TRT = ifelse(bioreptable[,"CKD"] %in% "Yes", bioreptable[,"TRT"], NA))
addontable13 <- data.frame(PATNUM = SOIall, CUSTOM_ACEIandARB = ifelse(bioreptable[,"MEAHACE"] %in% "Yes" | bioreptable[,"MEAHARB"] %in% "Yes", "ACEIorARB", "NoACEIorARB"))
addontable14 <- data.frame(PATNUM = SOIall, CUSTOM_DEGRISCH_NONEMILD = ifelse(bioreptable[,"DEGRISCH"] %in% c("None", "Mild"), "NoneMild", bioreptable[,"DEGRISCH"]))
addontable15 <- data.frame(PATNUM = SOIall, CUSTOM_IMGDEGIS_NONEMILD = ifelse(bioreptable[,"IMGDEGIS"] %in% c("None", "Mild"), "NoneMild", bioreptable[,"IMGDEGIS"]))
# addontable16 <- data.frame(PATNUM = SOIall, DUKESCORE_NUMERIC = ifelse(bioreptable[,"DUKESCORE"] %in% c("Mild", "None"), "NoneMild", bioreptable[,"IMGDEGIS"]))
#
#
# tt1 <- align_metatable(intable = bioreptable[bioreptable[,"PATNUM"] %in% SOIall, "DUKESCORE", drop=FALSE], list(
# "DUKESCORE" = list("DUKESCORE_7" = "Left Main >=50%",
# "DUKESCORE_6" = "3 Vessels with Severe (>=70%) Plaque or 2 Severe (>=70%) Plaque Including Proximal LAD",
# "DUKESCORE_5" = "3 Vessels with at least Moderate (>=50%) Plaque or 2 Severe (>=70%) Plaque or Severe (>=70%) Proximal LAD Plaque",
# "DUKESCORE_4" = "2 Vessels with at least Moderate (>=50%) Plaque or 1 Severe (>=70%) Plaque",
# "DUKESCORE_3" = "1 Vessel with at least Moderate (>=50%) Plaque")))
# Adding on some cleaned columns of heart disease variables
IMGDEGIS_addontable <- bioreptable[,c("PATNUM", "IMGDEGIS"), drop=FALSE]
IMGDEGIS_addontable[,"IMGDEGIS_01_2_3"] <- ifelse(IMGDEGIS_addontable[,"IMGDEGIS"] %in% c("None", "Mild"), "NoneMild",
ifelse(IMGDEGIS_addontable[,"IMGDEGIS"] %in% "Moderate", "Moderate",
ifelse(IMGDEGIS_addontable[,"IMGDEGIS"] %in% "Severe", "Severe", NA)))
IMGDEGIS_addontable[,"IMGDEGIS_01_3"] <- ifelse(IMGDEGIS_addontable[,"IMGDEGIS"] %in% c("None", "Mild"), "NoneMild",
ifelse(IMGDEGIS_addontable[,"IMGDEGIS"] %in% "Severe", "Severe", NA))
CTNDV50_addontable <- bioreptable[,c("PATNUM", "CTNDV50"), drop=FALSE]
CTNDV50_addontable[,"CTNDV50_123_clean"] <- ifelse(CTNDV50_addontable[,"CTNDV50"] %in% "1", "1",
ifelse(CTNDV50_addontable[,"CTNDV50"] %in% "2", "2",
ifelse(CTNDV50_addontable[,"CTNDV50"] %in% "3", "3", NA)))
CTNDV50_addontable[,"CTNDV50_13_clean"] <- ifelse(CTNDV50_addontable[,"CTNDV50"] %in% "1", "1",
ifelse(CTNDV50_addontable[,"CTNDV50"] %in% "3", "3", NA))
CTNDV70_addontable <- bioreptable[,c("PATNUM", "CTNDV70"), drop=FALSE]
CTNDV70_addontable[,"CTNDV70_0123_clean"] <- ifelse(CTNDV70_addontable[,"CTNDV70"] %in% "0", "0",
ifelse(CTNDV70_addontable[,"CTNDV70"] %in% "1", "1",
ifelse(CTNDV70_addontable[,"CTNDV70"] %in% "2", "2",
ifelse(CTNDV70_addontable[,"CTNDV70"] %in% "3", "3", NA))))
CTNDV70_addontable[,"CTNDV70_13_clean"] <- ifelse(CTNDV70_addontable[,"CTNDV70"] %in% "1", "1",
ifelse(CTNDV70_addontable[,"CTNDV70"] %in% "3", "3", NA))
CTNDV70_addontable[,"CTNDV70_combo0noneval"] <- ifelse(CTNDV70_addontable[,"CTNDV70"] %in% c("Non-evaluable", "0"), "0orNoneval",
ifelse(CTNDV70_addontable[,"CTNDV70"] %in% c(""), NA, CTNDV70_addontable[,"CTNDV70"]))
## Also adding on the clustermembership tables to this:
# rna_clustermembership_table, meth_clustermembership_table
print(addclustertypes)
if (addclustertypes) {
rna_clustermembership_addon <- data.frame(PATNUM = SOIall, rna_clustermembership_table[SOIall, c("rna_4cluster_w3AB", "rna_4cluster")])
meth_clustermembership_addon <- data.frame(PATNUM = SOIall, meth_clustermembership_table[SOIall, c("meth_3cluster", "meth_4cluster")])
} else {
rna_clustermembership_addon <- meth_clustermembership_addon <- NULL
}
bioreptable_waddons <- Reduce(function(dtf1, dtf2) merge(dtf1, dtf2, by = "PATNUM", all = TRUE, sort = FALSE),
Filter(Negate(is.null), list( # remove the null entries0
bioreptable,
addontable1, addontable2, addontable3, addontable4, # addontable5,
addontable6, addontable7, addontable8, addontable9, addontable9_2, addontable10,
addontable11, addontable12, addontable13, addontable14, addontable15,
biomarkertable_sel,
IMGDEGIS_addontable[,c("PATNUM", "IMGDEGIS_01_2_3", "IMGDEGIS_01_3")],
CTNDV50_addontable[,c("PATNUM", "CTNDV50_123_clean", "CTNDV50_13_clean")],
CTNDV70_addontable[,c("PATNUM", "CTNDV70_0123_clean", "CTNDV70_13_clean", "CTNDV70_combo0noneval")],
rna_clustermembership_addon, meth_clustermembership_addon
)))
rownames(bioreptable_waddons) <- bioreptable_waddons[,"PATNUM"]
## Change the event columns to characters for proper tabulations:
cols_to_characterify <- c(colnames(bioreptable_waddons)[grepl("^C_", colnames(bioreptable_waddons))], "PRICEREB")
bioreptable_waddons[,cols_to_characterify] <- apply(bioreptable_waddons[,cols_to_characterify], 2, function(x) as.character(x))
# Make all NA values set to NotAvailable
# tt1 <- bioreptable_waddons
return(bioreptable_waddons)
}
# --------------------------------- Factorize our biorep table with preset levels ---------------------------------
# Create a factorized table for whenever that particular things matters (with presets ready to go)
factorize_metatable <- function(intable) {
outtable <- intable
COInames <- colnames(outtable)
if ("IMGDEGIS" %in% COInames) {outtable[,"IMGDEGIS"] <- factor(outtable[,"IMGDEGIS"], levels = c("None", "Mild", "Moderate", "Severe"))}
if ("IMGDEGIS_01_2_3" %in% COInames) {outtable[,"IMGDEGIS_01_2_3"] <- factor(outtable[,"IMGDEGIS_01_2_3"], levels = c("NoneMild", "Moderate", "Severe"))}
if ("IMGDEGIS_01_3" %in% COInames) {outtable[,"IMGDEGIS_01_3"] <- factor(outtable[,"IMGDEGIS_01_3"], levels = c("NoneMild", "Severe"))}
if ("CTNDV50" %in% COInames) {outtable[,"CTNDV50"] <- factor(outtable[,"CTNDV50"], levels = c("1", "2", "3", "Non-evaluable"))}
if ("CTNDV50_123_clean" %in% COInames) {outtable[,"CTNDV50_123_clean"] <- factor(outtable[,"CTNDV50_123_clean"], levels = c("1", "2", "3"))}
if ("CTNDV50_13_clean" %in% COInames) {outtable[,"CTNDV50_13_clean"] <- factor(outtable[,"CTNDV50_13_clean"], levels = c("1", "3"))}
if ("CTNDV70" %in% COInames) {outtable[,"CTNDV70"] <- factor(outtable[,"CTNDV70"], levels = c("Non-evaluable", "0", "1", "2", "3"))}
if ("CTNDV70_combo0noneval" %in% COInames) {outtable[,"CTNDV70_combo0noneval"] <- factor(outtable[,"CTNDV70_combo0noneval"], levels = c("0orNoneval", "1", "2", "3"))}
if ("CKD" %in% COInames) {outtable[,"CKD"] <- factor(outtable[,"CKD"], levels = c("No", "Yes"))}
if ("highlowage" %in% COInames) {outtable[,"highlowage"] <- factor(outtable[,"highlowage"], levels = c("AGE_RAND_low", "AGE_RAND_highQ3"))}
if ("rna_4cluster_w3AB" %in% COInames) {outtable[,"rna_4cluster_w3AB"] <- factor(outtable[,"rna_4cluster_w3AB"],
levels = c("nmf_cluster_1", "nmf_cluster_2", "nmf_cluster_3A", "nmf_cluster_3B", "nmf_cluster_4"))}
if ("rna_4cluster" %in% COInames) {outtable[,"rna_4cluster"] <- factor(outtable[,"rna_4cluster"],
levels = c("nmf_cluster_1", "nmf_cluster_2", "nmf_cluster_3", "nmf_cluster_4"))}
if ("meth_3cluster" %in% COInames) {outtable[,"meth_3cluster"] <- factor(outtable[,"meth_3cluster"],
levels = c("meth_3cluster_1", "meth_3cluster_2", "meth_3cluster_3"))}
if ("meth_4cluster" %in% COInames) {outtable[,"meth_4cluster"] <- factor(outtable[,"meth_4cluster"],
levels = c("meth_4cluster_1", "meth_4cluster_2", "meth_4cluster_3", "meth_4cluster_4"))}
if ("CAGE_RND" %in% COInames) {outtable[,"CAGE_RND"] <- factor(outtable[,"CAGE_RND"],
levels = c("<= 34", "35 - 44", "45 - 54", "55 - 64", "65 - 74", ">= 75"))}
if ("SEX" %in% COInames) {outtable[,"SEX"] <- factor(outtable[,"SEX"], levels = c("Female", "Male"))}
if ("RACE" %in% COInames) {outtable[,"RACE"] <- factor(outtable[,"RACE"],
levels = c("White", "American Indian or Alaska Native", "Black or African American", "Asian", "Native Hawaiian or Other Pacific Islander",
"Multiple Races", ""))}
return(outtable)
}
# --------------------------------- custom heatmap color annotation list from the color guide and COI ---------------------------------
# Create heatmap annotation custom list from the colorguide and selected COI
custom_annotation_list_from_colorguide <- function(COI, colorguide) {
COIlist <- list()
for (COInum in seq_len(length(COI))) {
COIsel <- COI[COInum]
COIlist[COInum] <- list(colorguide[colorguide[,"category"] %in% COIsel,"color"])
names(COIlist[[COInum]]) <- colorguide[colorguide[,"category"] %in% COIsel,"feature"]
names(COIlist)[COInum] <- COIsel
}
return(COIlist)
}
# --------------------------------- ischemia disease metric plot ---------------------------------
# Second viz - the overlap of the ischemia/CT variables - I really think that is a useful viz
ischemia_disease_metrics_plot <- function(bioreptable_waddons, colorguide, plotmetrics = c("IMGDEGIS_01_2_3", "CTNDV70_combo0noneval")) {
# create a factorized metatable for our variables of interest, factors preserve order
labeltable_temp <- factorize_metatable(bioreptable_waddons[,plotmetrics])
# Add in NotAvailable instead of NA to make sorting better
labeltable <- do.call(cbind.data.frame, lapply(labeltable_temp, function(x) {
factor(ifelse(is.na(x), "NotAvailable", as.character(x)), levels = c("NotAvailable", levels(x)))
}))
rownames(labeltable) <- rownames(labeltable_temp)
labeltable <- labeltable[rev(do.call(order, labeltable)),]
customcolorlist <- custom_annotation_list_from_colorguide(COI = plotmetrics, colorguide)
annotationlist1 <- annotationlist_builder(labeltable, customcolorlist = customcolorlist)
## Dummy table to work with function.
dummytab <- labeltable
dummytab[] <- 1
labelplot <- create_heatmap(counttab = dummytab, subsetnum = FALSE, scale_data = FALSE, colmetatable = NULL, colannotationlist = NULL,
rowmetatable = labeltable, rowannotationlist = annotationlist1,
colclusterparam = FALSE, rowclusterparam = FALSE, separate_legend = FALSE, heatmapcolorparam = NULL)
return(labelplot)
}
# --------------------------------- In group vs Out group enrichment tests ---------------------------------
ingroup_vs_outgroup_cohort_enrichment_tests <- function(tabulation_table, group_column, cohort_tabulations_outpath) {
summary_table_pval_outlist <- summary_table_sign_outlist <- summary_table_ratio_outlist <- summary_ci_table_outlist <- list()
for (nmfnum in seq_len(length(sort(unique(na.omit(tabulation_table[,group_column])))))) {
nmfsel <- sort(unique(na.omit(tabulation_table[,group_column])))[nmfnum]
# tabulation_table_sel <- tabulation_table[SOIrna,]
tabulation_table_sel <- tabulation_table
tabulation_table_sel[,group_column] <- ifelse(tabulation_table_sel[,group_column] == nmfsel, nmfsel, paste0("NOT_", nmfsel))
summarystatfile <- paste0(cohort_tabulations_outpath, "COI_tabulation_", "group_column", "_", nmfsel, ".csv")
sumstattab_seq <- summarize_table(intable = tabulation_table_sel, groupvar = group_column,
outfile = summarystatfile, calc_stats = TRUE, calc_ci = TRUE)
collapsed_summary_table <- cbind(category = rep(names(sumstattab_seq), lapply(sumstattab_seq, nrow)), do.call(rbind.fill, sumstattab_seq))
collapsed_summary_table[collapsed_summary_table[,paste0(group_column, "_cat")] == "Min.", paste0(group_column, "_cat")] <- "NUMERIC"
collapsed_summary_table[,"combined_catval"] <- apply(collapsed_summary_table[,c("category", paste0(group_column, "_cat"))], 1,
function(x) paste(x, collapse = "__"))
## First one - is a pval table
summary_table_pval <- collapsed_summary_table[!collapsed_summary_table[,"statval"] %in% c(NA, ""),c("category", paste0(group_column, "_cat"), "statval", "combined_catval")]
summary_table_pval_outlist[[nmfnum]] <- cbind(summary_table_pval[,c("combined_catval", "statval")], cluster = nmfsel)
names(summary_table_pval_outlist)[nmfnum] <- nmfsel
## Second one - is a CI table
summary_table_ci_val <- collapsed_summary_table[!collapsed_summary_table[,"ci_val"] %in% c(NA, ""),c("category", paste0(group_column, "_cat"), "ci_val", "combined_catval")]
summary_ci_table_outlist[[nmfnum]] <- cbind(summary_table_ci_val[,c("combined_catval", "ci_val")], cluster = nmfsel)
names(summary_ci_table_outlist)[nmfnum] <- nmfsel
## For each category -
signoutlist <- ratiooutlist <- list()
for (combined_catval_num in seq_len(length(summary_table_pval[,"combined_catval"]))) {
combined_catval_sel <- summary_table_pval[,"combined_catval"][combined_catval_num]
if (grepl("__NUMERIC", combined_catval_sel)) {
catsel <- gsub("NUMERIC", "Mean", combined_catval_sel)
datasel <- collapsed_summary_table[collapsed_summary_table[,"combined_catval"] == catsel,]
signout <- ifelse(datasel[,nmfsel] > datasel[,paste0("NOT_", nmfsel)], 1, -1)
# ratioout <- log2(as.numeric(datasel[,nmfsel]) / as.numeric(datasel[,paste0("NOT_", nmfsel)]))
# if (is.infinite(ratioout)) {ratioout <- 10 * sign(ratioout)}
ratioout <- as.numeric(datasel[,nmfsel]) / as.numeric(datasel[,paste0("NOT_", nmfsel)])
if (is.infinite(ratioout)) {ratioout <- 10}
} else {
datasel <- collapsed_summary_table[collapsed_summary_table[,"combined_catval"] == combined_catval_sel,]
outratios <- as.numeric(unlist(datasel[,c(nmfsel, paste0("NOT_", nmfsel))])) /
# as.numeric(unlist(collapsed_summary_table[collapsed_summary_table[,"combined_catval"] == "PATNUM__total",
# c(nmfsel, paste0("NOT_", nmfsel))]))
as.numeric(unlist(collapsed_summary_table[grepl("__total", collapsed_summary_table[,"combined_catval"]),
c(nmfsel, paste0("NOT_", nmfsel))]))
signout <- ifelse(outratios[1] > outratios[2], 1, -1)
# ratioout <- log2(outratios[1] / outratios[2])
# if (is.infinite(ratioout)) {ratioout <- 10 * sign(ratioout)}
ratioout <- outratios[1] / outratios[2]
if (is.infinite(ratioout)) {ratioout <- 10}
}
signoutlist[[combined_catval_num]] <- data.frame(combined_catval = combined_catval_sel, cluster = nmfsel, statsign = as.numeric(signout))
ratiooutlist[[combined_catval_num]] <- data.frame(combined_catval = combined_catval_sel, cluster = nmfsel, ratio = as.numeric(ratioout))
names(signoutlist)[combined_catval_num] <- names(ratiooutlist)[combined_catval_num] <- combined_catval_sel
}
signouttable <- do.call(rbind, signoutlist)
summary_table_sign_outlist[[nmfnum]] <- signouttable
names(summary_table_sign_outlist)[nmfnum] <- nmfsel
ratioouttable <- do.call(rbind, ratiooutlist)
summary_table_ratio_outlist[[nmfnum]] <- ratioouttable
names(summary_table_ratio_outlist)[nmfnum] <- nmfsel
# summary_table_value <- collapsed_summary_table[!summary_table_pval[,"statval"] %in% c(NA, ""),c("category", "rnacluster_cat", "statval")]
# summary_table_pval[summary_table_pval[,"rnacluster_cat"] == "Min.","rnacluster_cat"] <- "NUMERIC"
}
# Summary sign out table
summary_table_sign_temp <- do.call(rbind, summary_table_sign_outlist)
summary_table_sign_temp2 <- dcast(summary_table_sign_temp, combined_catval ~ cluster, value.var = "statsign")
summary_table_sign_FULL <- apply(summary_table_sign_temp2[,2:ncol(summary_table_sign_temp2)], 2, function(x) as.numeric(as.character(x)))
rownames(summary_table_sign_FULL) <- summary_table_sign_temp2[,"combined_catval"]
summary_table_sign_FULL <- summary_table_sign_FULL[summary_table_pval_outlist[[1]][,1], ]
# ratios instead of signs
summary_table_ratio_temp <- do.call(rbind, summary_table_ratio_outlist)
summary_table_ratio_temp2 <- dcast(summary_table_ratio_temp, combined_catval ~ cluster, value.var = "ratio")
summary_table_ratio_FULL <- apply(summary_table_ratio_temp2[,2:ncol(summary_table_ratio_temp2)], 2, function(x) as.numeric(as.character(x)))
rownames(summary_table_ratio_FULL) <- summary_table_ratio_temp2[,"combined_catval"]
summary_table_ratio_FULL <- summary_table_ratio_FULL[summary_table_pval_outlist[[1]][,1], ]
summary_table_pval_temp <- do.call(rbind, summary_table_pval_outlist)
summary_table_pval_temp2 <- dcast(summary_table_pval_temp, combined_catval ~ cluster, value.var = "statval")
summary_table_pval_FULL <- apply(summary_table_pval_temp2[,2:ncol(summary_table_pval_temp2)], 2, function(x) as.numeric(as.character(x)))
rownames(summary_table_pval_FULL) <- summary_table_pval_temp2[,"combined_catval"]
summary_table_pval_FULL <- summary_table_pval_FULL[summary_table_pval_outlist[[1]][,1], ]
summary_table_cival_temp <- do.call(rbind, summary_ci_table_outlist)
summary_table_cival_temp2 <- dcast(summary_table_cival_temp, combined_catval ~ cluster, value.var = "ci_val")
summary_table_cival_FULL <- apply(summary_table_cival_temp2[,2:ncol(summary_table_cival_temp2)], 2, function(x) as.character(x))
rownames(summary_table_cival_FULL) <- summary_table_cival_temp2[,"combined_catval"]
summary_table_cival_FULL <- summary_table_cival_FULL[summary_ci_table_outlist[[1]][,1], ]
# Return just the CI values (no mean)
summary_table_cival_FULL_out <- summary_table_cival_FULL
summary_table_cival_FULL_out[] <- apply(summary_table_cival_FULL_out, c(1,2), function(x) sub(".*? ", "", x))
# summary_table_pval_FULL_signed <- summary_table_pval_FULL * summary_table_sign_FULL
summary_table_pval_FULL_signed <- summary_table_ratio_FULL
# summary_table_pval_FULL_filtered <- summary_table_pval_FULL
summary_table_pval_FULL_filtered_signed <- summary_table_ratio_FULL
summary_table_pval_FULL_filtered_signed[summary_table_pval_FULL > 0.05] <- NA
# summary_table_pval_FULL_filtered_signed <- summary_table_pval_FULL_filtered * summary_table_sign_FULL
return(list(summary_table_pval_FULL_filtered_signed = summary_table_pval_FULL_filtered_signed,
summary_table_cival_FULL_out = summary_table_pval_FULL_filtered_signed,
summary_table_pval_FULL_signed = summary_table_pval_FULL_signed))
}
# --------------------------------- hazard ratio heatmap ---------------------------------
hr_heatmap <- function(hr_table) {
## Lets output a cleaned version of the cumhazouttable, and a heatmap with the CI and text within it
# tt1 <- data.frame(fullcumhazouttable)
genestoagg <- unique(gsub("_.*", "", rownames(fullcumhazouttable)))
## I can definitely aggregate this, but idk how, so I am gonna use a forloop instead.
HRoutlist <- textoutlist <- list()
for (genenum in seq_len(length(genestoagg))) {
## Grab the rows we need
genesel <- genestoagg[genenum]
selrows <- fullcumhazouttable[grepl(genesel, rownames(fullcumhazouttable)),]
## Output to a new table
# textoutlist[[genenum]] <- apply(selrows, 2, function(x){paste0(round(x[1], 2), " (",round(x[2], 2), " - ", round(x[3], 2), ")")})
## Lets try just the CIs
textoutlist[[genenum]] <- apply(selrows, 2, function(x){paste0("(",round(x[2], 2), " - ", round(x[3], 2), ")")})
names(textoutlist)[genenum] <- genesel
## Write out just the HR to a list
HRoutlist[[genenum]] <- selrows[grepl("_exp", rownames(selrows)),]
names(HRoutlist)[genenum] <- genesel
}
HRtable <- hr_table
HRtexttable <- do.call(rbind, textoutlist)
heatmapcolorparam <- colorRamp2(c(0, 1, 6), c( "#0000A7", "White", "#A30000"))
hrmap = Heatmap(HRtable[rownames(maptab),],
border = TRUE,
rect_gp = gpar(col = "black", lwd = 1),
col = heatmapcolorparam, ## Define the color scale for the heatmap
row_title = "Gene", ## Name the rows
column_title = "Event", ## Name the columns
cluster_columns = FALSE, ## Cluster the columns or leave as is
cluster_rows = FALSE, ## Cluster the rows or leave as is
show_column_names = TRUE , ## Show the Column Names
column_names_gp = gpar(fontsize = 6), ## Change the size of the column names
show_row_names = TRUE, ## Show the row names
row_names_side = "left", ## Place the row names on the Left side of the heatmap
row_names_gp = gpar(fontsize=6),
heatmap_legend_param = list(
title = "Hazard Ratio",
legend_height = unit(2.5, "cm"),
title_gp = gpar(fontsize = 8, fontface = "bold")),
height = unit(20,"cm"),
width = unit(10,"cm"),
## Adds in the cor value from the maptab
# cell_fun = function(j, i, x, y, width, height, fill) {
# grid.text(paste0(sprintf("%.2f", t(moduleTraitCor)[,colnames(maptab),drop=FALSE][i, j]), "\n", "(",
# sprintf("%.2f", t(moduleTraitPvalue)[,colnames(maptab),drop=FALSE][i, j]), ")"),
# x, y, gp = gpar(fontsize = 8))
# }
cell_fun = function(j, i, x, y, width, height, fill) {
# grid.text(paste0(sprintf("%.2f", moduleTraitCor[i, j]), "\n", "(",
# sprintf("%.2f", moduleTraitPvalue[i, j]), ")"),
grid.text(HRtexttable[rownames(maptab),][i, j],
x, y, gp = gpar(fontsize = 6))
}
)
hmoutfile2 <- paste0(outfilepathsurvival, "HR_heatmap.pdf")
# hmoutfile <- paste0(outfilepathsurvival, "CORRECTED_event_heatmap_log2fcsort_with_annot.pdf")
pdf(hmoutfile2, 11, 9)
draw(hrmap)
junk <- dev.off()
}
# --------------------------------- cluster module meta summary heatmap ---------------------------------
cluster_module_meta_summary_heatmap_function <- function(ingenestocolortable, incounttable, bioreptable_waddons,
selected_clusterlabel, eigengeneorder, metacols_sel, ...) {
## Read in eigengene table
# GOI <- rownames(ingenestocolortable[ingenestocolortable[,"moduleColors"] != "grey",]) ## Only plotting on genes that are NOT grey
GOI <- rownames(ingenestocolortable[ingenestocolortable[,"moduleColors"] %in% eigengeneorder,]) ## Only plotting on genes that are NOT grey
GOI <- GOI[GOI %in% rownames(incounttable)]
plotSOI <- colnames(incounttable)
# Now lets make a summary - where we have a split heatmap - with modules labeled and split on rows, and then sample labeled and split on columns
hmplottab <- incounttable[GOI, plotSOI]
colsplitparam <- factor(bioreptable_waddons[plotSOI, selected_clusterlabel])
rowsplitparam <- factor(ingenestocolortable[GOI,"moduleColors"], levels = eigengeneorder)
sampleannottable <- merge(bioreptable_waddons[plotSOI, metacols_sel],
bioreptable_waddons[plotSOI, selected_clusterlabel, drop=FALSE], by = "row.names")
rownames(sampleannottable) <- sampleannottable[,"Row.names"]
sampleannottable <- sampleannottable[plotSOI,!grepl("Row.names", colnames(sampleannottable))]
## Make the annotation (the main plot we want)
sampleannotationlist <- custom_annotation_list_from_colorguide(COI = colnames(sampleannottable), colorguide)
## Top annotation
temp1 <- vector("list", length(sampleannotationlist))
names(temp1) = names(sampleannotationlist)
annotlegendlist = lapply(temp1, function(x) x[[1]] =
list(title_gp=gpar(fontsize=5, fontface="bold"), labels_gp=gpar(fontsize=4)))
# ## ADDED 03-24-2022 - keeps the order of the annotationlist for the legend order
for (annotnum in seq_len(length(annotlegendlist))) {
annotname_select <- names(annotlegendlist)[annotnum]
if (!is.null(names(sampleannotationlist[[annotname_select]]))) {
annotlegendlist[[annotnum]] <- c(annotlegendlist[[annotnum]], list(at = names(sampleannotationlist[[annotname_select]])))
} else {next}
}
## ADDED 03-24-2022 - keeps the order of the annotationlist for the legend order
## Define a param that will go through each annotation - and keep a legend if its continuous or has less than 10 discrete terms, otherwise hide the legend
showlegendparam = unname(unlist(lapply(sampleannotationlist, function(x) {
numterms = tryCatch(length(na.omit(unique(x))), error=function(e) NULL)
is.null(numterms) || numterms <= 10})))
hatop = HeatmapAnnotation(df = sampleannottable,
col = sampleannotationlist,
na_col = "white",
show_annotation_name = TRUE,
annotation_name_gp = gpar(fontsize = 8, fontface="bold"),
annotation_name_side = "left",
simple_anno_size = unit(min(60/length(sampleannotationlist), 5),"mm"),
show_legend = TRUE,
annotation_legend_param = annotlegendlist)
# gene annotation
geneannottable <- ingenestocolortable[GOI,"moduleColors", drop=FALSE]
genecustomcolorlist <- list(moduleColors = eigengeneorder)
names(genecustomcolorlist[["moduleColors"]]) <- eigengeneorder
geneannotationlist <- annotationlist_builder(geneannottable, customcolorlist = genecustomcolorlist)
## Side annotation
## Define parameters for each of the labels on the annotation bars
temp1 <- vector("list", length(geneannotationlist))
names(temp1) = names(geneannotationlist)
annotlegendlist = lapply(temp1, function(x)
x[[1]] = list(title_gp=gpar(fontsize=8, fontface="bold"), labels_gp=gpar(fontsize=8)))
# ## ADDED 03-24-2022 - keeps the order of the annotationlist for the legend order
for (annotnum in seq_len(length(annotlegendlist))) {
annotname_select <- names(annotlegendlist)[annotnum]
if (!is.null(names(geneannotationlist[[annotname_select]]))) {
annotlegendlist[[annotnum]] <- c(annotlegendlist[[annotnum]], list(at = names(geneannotationlist[[annotname_select]])))
} else {next}
}
## ADDED 03-24-2022 - keeps the order of the annotationlist for the legend order
## Define a param that will go through each annotation - and keep a legend if its continuous or has less than 10 discrete terms, otherwise hide the legend
showlegendparam = unname(unlist(lapply(geneannotationlist, function(x) {
numterms = tryCatch(length(na.omit(unique(x))), error=function(e) NULL)
is.null(numterms) || numterms <= 10})))
## Look for any empty annotations - fill them with white, and later, make sure to hide their legend
emptyannots = names(sapply(geneannotationlist, length)[sapply(geneannotationlist, length)==0])
if (length(emptyannots) > 0){
for (i in 1:length(emptyannots)) {
temp1 = "white"
names(temp1) = emptyannots[i]
geneannotationlist[[emptyannots[i]]] = temp1
}
showlegendparam[which(names(geneannotationlist) %in% emptyannots)] = FALSE
}
## Add param that will bolden the side annotation bars if it is <100, and omit the grid lines if more
if (nrow(geneannottable) < 100) {
sideannotation_linebold_param <- gpar(fontsize = 0.5)} else {sideannotation_linebold_param <- NULL}
haside = rowAnnotation(df = geneannottable,
col = geneannotationlist,
na_col = "white",
# gp = gpar(fontsize = 0.01),
gp = sideannotation_linebold_param,
show_annotation_name=TRUE,
annotation_name_gp = gpar(fontsize = 8, fontface="bold"),
annotation_name_side = "top",
simple_anno_size = unit(min(60/length(geneannotationlist), 5),"mm"),
show_legend = TRUE,
annotation_legend_param = annotlegendlist)
hmplottab = as.matrix(t(apply(hmplottab, 1, function(x) zscore(x))))
heatmapcolorparam <- colorRamp2(breaks = c(4, 0, -4), c("darkred", "white", "darkblue"))
summary_outhm <- Heatmap(as.matrix(hmplottab),
col = heatmapcolorparam,
row_title = "Genes",column_title = "Samples",
row_split = rowsplitparam, column_split = colsplitparam,
top_annotation = hatop,
cluster_columns = TRUE, cluster_rows = TRUE,
cluster_row_slices = FALSE, cluster_column_slices = FALSE,
show_row_dend = FALSE, show_column_dend = FALSE,
# rect_gp = gpar(col = "black", lwd = 0.5),
show_column_names = FALSE, column_names_gp = gpar(fontsize = 6),
show_row_names = FALSE,
heatmap_legend_param = list(
title = "Zscore",
title_gp = gpar(fontsize = 8, fontface = "bold")),
height = unit(min((nrow(hmplottab)/2), 12),"cm"),
width = unit(min(ncol(hmplottab), 18),"cm")
)
out1 <- draw(summary_outhm + haside, annotation_legend_side = "bottom", padding = unit(c(5, 20, 5, 5), "mm"))
return(out1)
# pdf(paste0(outfilepathintegration, "nmf_eigen_meta_summary_heatmap.pdf"), useDingbats = FALSE, width = 20, height = 15)
# draw(summary_outhm + haside)
# junk <- dev.off()
}
# --------------------------------- eigengene vs cluster heatmap ---------------------------------
eigen_v_cluster_heatmap <- function(eigengenecounttable, selected_clusterlabel, eigengeneorder, colorguide) {
# this is the plottable that we need
hmplottable <- t(eigengenecounttable[,paste0("ME", eigengeneorder)])
plotSOI <- colnames(hmplottable)
# But i also want the rank table by cluster, so i need a box plot style melted table, and then go from there
temptab <- na.omit(merge(bioreptable_waddons[,selected_clusterlabel, drop = FALSE], eigengenecounttable, by = "row.names"))
rownames(temptab) <- temptab[,"Row.names"]
temptab <- temptab[,!grepl("Row.names", colnames(temptab))]
cluster_eigenrank_table_value <- aggregate(temptab[,colnames(eigengenecounttable)], by = list(temptab[,selected_clusterlabel]), mean)
rownames(cluster_eigenrank_table_value) <- cluster_eigenrank_table_value[,"Group.1"]
cluster_eigenrank_table_value <- cluster_eigenrank_table_value[,!grepl("Group.1", colnames(cluster_eigenrank_table_value))]
# I think I want to output a helper table here - that will give relative values between them
## Namely, I want these as scaled (???) do I?? values, but most importantly, I want the difference between the highest value, and the NEXT highest value ...
max_minus_next_diff_table <- data.frame(t(apply(cluster_eigenrank_table_value, 2, function(x) {
# x <- cluster_eigenrank_table_value[,1]
# rankvals <- rank(x)
max_minus_next_diff <- x[which.max(x)] - x[-which.max(x)][which.max(x[-which.max(x)])]
maxval <- paste0("meth_3cluster_", which.max(x))
c(maxval, max_minus_next_diff)
})))
colnames(max_minus_next_diff_table) <- c("maxcluster", "max_minus_next_diff")
max_minus_next_diff_table <- max_minus_next_diff_table[paste0("ME", eigengeneorder),,drop=FALSE]
max_minus_next_diff_table <- max_minus_next_diff_table[rev(order(max_minus_next_diff_table[,"maxcluster"],
-as.numeric(max_minus_next_diff_table[,"max_minus_next_diff"]), decreasing = TRUE)),,drop=FALSE]
# max_minus_next_diff_table
# max_minus_next_diff_table <- max_minus_next_diff_table[order(max_minus_next_diff_table[,"max_minus_next_diff"], decreasing = TRUE),,drop=FALSE]
# max_minus_next_diff_table <- max_minus_next_diff_table[order(max_minus_next_diff_table[,"max_minus_next_diff"], decreasing = TRUE),]
cluster_eigenrank_table_rank <- data.frame(apply(cluster_eigenrank_table_value, 2, function(x) rev(rank(x))))
# Gives an attempt at ordering - will probably need to be manually ordered though
cluster_eigenrank_table_rank <- data.frame(t(cluster_eigenrank_table_rank[,do.call(order, data.frame(t(cluster_eigenrank_table_rank)))]))
# col annotation is just the cluster labels (easy)
colmetatable <- bioreptable_waddons[plotSOI, selected_clusterlabel, drop = FALSE]
colsplitparam <- data.frame(factor(bioreptable_waddons[plotSOI, selected_clusterlabel]))
dimnames(colsplitparam) <- list(plotSOI, selected_clusterlabel)
colannotationlist <- custom_annotation_list_from_colorguide(COI = selected_clusterlabel, colorguide)
# USING THIS RANK TABLE for annotation
# Black to white color range
rowmetatable <- cluster_eigenrank_table_rank[paste0("ME", eigengeneorder), names(colannotationlist[[selected_clusterlabel]])]
blackwhite_color_range <- colorRampPalette(c("#e5e5e5", "#191919"))
rowcustomcolorlist <- rep(list(colorRamp2(breaks = sort(unique(unlist(rowmetatable))),
# colors = brewer.pal(length(unique(unlist(rowmetatable))), "Greys")
colors = blackwhite_color_range(length(unique(unlist(rowmetatable))))
)),
length(unique(unlist(rowmetatable))))
names(rowcustomcolorlist) <- colnames(rowmetatable)
rowannotationlist <- annotationlist_builder(rowmetatable, customcolorlist = rowcustomcolorlist)
#' customcolorlist = list(A = c("high" = "red", "low" = "blue"),
#' #' B = circlize::colorRamp2(seq(-5, 5, length = 3),
#' #' RColorBrewer::brewer.pal(3, "Reds")))
heatmapcolorparam <- colorRamp2(c(-0.1, 0, 0.1), c("blue", "white", "red"))
outhm1 <- create_heatmap(counttab = hmplottable, scale_data = FALSE, separate_legend = FALSE,
colmetatable = colmetatable, colannotationlist = colannotationlist,
rowmetatable = rowmetatable, rowannotationlist = rowannotationlist,
colclusterparam = TRUE, rowclusterparam = FALSE,
heatmapcolorparam = heatmapcolorparam,
columnsplitparam = colsplitparam)
return(list(heatmap = outhm1[[1]], cluster_eigenrank_table_rank = rowmetatable,
max_minus_next_diff_table = max_minus_next_diff_table, cluster_eigenrank_table_value = cluster_eigenrank_table_value))
}
# --------------------------------- create boxplots for every feature by annotation column ---------------------------------
# Eigengene boxplots across cluster ... really boxplots for any annotation with a count table
## So input is a counttable, and each feature will get a boxplot, with the separate boxplots being pulled from an annotation table by column
## output will be N boxplot figures (N = features) by X folders (X = number of annotation columns)
## Also output the spearman correlation plot and values as well
## Need the outfilepath - cause we write out a bajillion boxplots, and dont want to save those all to and output object
boxplots_from_counttable_by_annotation <- function(counttable, boxplot_annotationtable, outfilepath,
calculate_corrvalues = FALSE,
bp_color_ref = NULL) {
# These are the features and annotations we will run over
bp_features <- rownames(counttable)
bp_annots <- colnames(boxplot_annotationtable)
params_grid <- expand.grid(bp_features, bp_annots)
colnames(params_grid) <- c("bp_features", "bp_annots")
wilcox_statoutlist <- spearman_statoutlist <- list()
for (params_num in seq_len(nrow(params_grid))) {
# for (params_num in 1:75) {
# Grab this runs parameters
param_sel <- params_grid[params_num,]
feature_sel <- param_sel[,"bp_features"]
annot_sel <- param_sel[,"bp_annots"]
dir.create(paste0(outfilepath, annot_sel, "/"), showWarnings = FALSE, recursive = TRUE)
counttable_sel <- t(counttable[feature_sel,,drop=FALSE])
annottable_sel <- boxplot_annotationtable[,annot_sel,drop=FALSE]
# nmf_sel <- nmf_clustermembership_table[,"combined",drop=FALSE]
bptab <- na.omit(merge(counttable_sel, annottable_sel, by = "row.names")[,c(3,1,2)])
bptab[,2] <- c("cohort")
## IF THE FIRST COL IS CONT (like for labs) - then split into quartiles
rawspearmanstatout <- NULL
if (is.numeric(bptab[,1])) {
## Also sneak in an actual corr with the raw values here jsut to see
scattertab <- bptab[,c(1,3)]
scattertab[,3] <- gsub("ME", "", colnames(scattertab)[2])
scatterout <- scatter_plotter(indata = scattertab[,c(1,2)], colorvar = scattertab[,3,drop=FALSE],
labsparam = list(title = paste0(feature_sel, " values for samples by ", annot_sel), x = annot_sel, y = feature_sel),
plotstats = TRUE)
pdf(paste0(outfilepath, annot_sel, "/", feature_sel, "_rawval_scatter.pdf"), useDingbats = FALSE)
print(scatterout)
junk <- dev.off()
## And capture this spearman value
rawspearmanstatval <- cor.test(scattertab[,1], scattertab[,2], method = "spearman", exact = FALSE)
rawspearmanstatout <- c(paste0(annot_sel, "_raw"), feature_sel, rawspearmanstatval$p.value, rawspearmanstatval$estimate)
## Create the bptab
cattab <- cut2(t(bptab[,1]),g=4)
levels(cattab)[match(levels(cattab)[1],levels(cattab))] <- paste0(annot_sel, "_Q1min")
levels(cattab)[match(levels(cattab)[2],levels(cattab))] <- paste0(annot_sel, "_Q2")
levels(cattab)[match(levels(cattab)[3],levels(cattab))] <- paste0(annot_sel, "_Q3")
levels(cattab)[match(levels(cattab)[4],levels(cattab))] <- paste0(annot_sel, "_Q4max")
bptab[,1] <- as.character(cattab)
}
## Pre calc the avg per group so we can sort in that order:
avgfeatvalue <- aggregate(bptab[,3], by = list(bptab[,1]), mean)
avgfeatvalue <- avgfeatvalue[order(avgfeatvalue[,2]),]
avgfeatvalue[,"Eigen_Score_Rank"] <- seq(1:nrow(avgfeatvalue))
colnames(avgfeatvalue) <- c("Group", "featurevalue", "group_feature_rank")
# Add custom coloring for this particular section
# bp_color_ref <- custom_annotation_list_from_colorguide(COI=group_column_selected, colorguide)
if (!is.null(bp_color_ref)){
if (annot_sel %in% names(bp_color_ref)) {
featorder_param <- names(bp_color_ref[[annot_sel]])
}
} else {
featorder_param <- levels(bptab[,1])
}
# Add custom coloring for this particular section
## OUTPUT THIS
bpout <- boxplot_plotter(boxplottable = bptab, xsplit = "category",
labsparam = list(title = paste0(feature_sel, " values for samples by ", annot_sel), x = annot_sel, y = feature_sel,
catorder = "cohort", featorder = featorder_param),
plotstats = "intra", testtypeparam = "wilcox.test"
)
# Add custom coloring for this particular section
# bp_color_ref <- custom_annotation_list_from_colorguide(COI=group_column_selected, colorguide)
if (!is.null(bp_color_ref)){
if (annot_sel %in% names(bp_color_ref)) {
bpout <- bpout + scale_fill_manual(breaks = names(bp_color_ref[[annot_sel]]), values = unname(bp_color_ref[[annot_sel]]))
}
}
# Add custom coloring for this particular section
pdf(paste0(outfilepath, annot_sel, "/", feature_sel, "_boxplot.pdf"), useDingbats = FALSE)
print(bpout)
junk <- dev.off()
# ## Save out the bptab
# bptablist[[params_num]] <- bptab
## Now we also want a corr plot if applicable?
if (calculate_corrvalues) {
scattertab <- bptab[,c(1,3)]
scattertab[,3] <- avgfeatvalue[,3][match(scattertab[,1], avgfeatvalue[,1])]
scattertab[,4] <- colnames(scattertab)[2]
scatterlabelparam <- as.vector(avgfeatvalue[,1])
names(scatterlabelparam) <- avgfeatvalue[,3]
scatterout <- scatter_plotter(indata = scattertab[,c(3,2)], colorvar = scattertab[,4,drop=FALSE],
labsparam = list(title = paste0(feature_sel, " values for samples by ", annot_sel), x = annot_sel, y = feature_sel),
plotstats = TRUE, addjitterparam = 0.1)
scatterout <- scatterout + scale_x_continuous(breaks = avgfeatvalue[,3], labels = avgfeatvalue[,1])
# scatterout <- scatterout + geom_point(alpha = 0.7, shape = 16, position = position_jitter(width = 0.1))
pdf(paste0(outfilepath, annot_sel, "/", feature_sel, "_scatter.pdf"), useDingbats = FALSE)
print(scatterout)
junk <- dev.off()
# Repeat for the spearman correlation
spearmanstatout <- cor.test(scattertab[,3], scattertab[,2], method = "spearman", exact = FALSE)
if (!is.null(rawspearmanstatout)) { ## Attach the raw spearman corr out as well if applicable
spearman_statoutlist[[params_num]] <- rbind(rawspearmanstatout, c(paste0(annot_sel, "_quartile"), feature_sel, spearmanstatout$p.value, spearmanstatout$estimate))
} else {
spearman_statoutlist[[params_num]] <- c(as.character(annot_sel), as.character(feature_sel),
spearmanstatout$p.value, spearmanstatout$estimate)
}
names(spearman_statoutlist)[params_num] <- feature_sel
}
# Grab the stats into a table
# Create the combinatorial table for all combos of the groups
# If this is a factor - then keep the levels of the factor for the order 2022-09-28
if (is.factor(bptab[,1])) {
combtab = combn(na.omit(levels(bptab[,1])), 2, simplify=F)
} else {
combtab = combn(as.character(unique(bptab[!is.na(bptab[,1]),1])), 2, simplify=F)
}
# Apply a functiona cross each combo using the bptab and pulling out each group
wilcoxstatsout <- lapply(combtab, function(x){
group1 <- bptab[bptab[,1] %in% x[1], 3]
group2 <- bptab[bptab[,1] %in% x[2], 3]
out1 <- c(as.character(annot_sel), x[1], x[2], as.character(feature_sel), wilcox.test(group1, group2)$p.value)
out2 <- cohens_d(group1, group2)
out3 <- c(mean(group1, na.rm = TRUE), mean(group2, na.rm = TRUE))
c(out1, out2, out3)
})
wilcox_statoutlist[[params_num]] <- do.call(rbind, wilcoxstatsout)
## Name all of our outlists
names(wilcox_statoutlist)[params_num] <- feature_sel
}
# # Cat our lists
wilcox_summarytable <- do.call(rbind, wilcox_statoutlist)
colnames(wilcox_summarytable) <- c("Cohort", "Feature1", "Feature2", "Feature", "wilcox_pval", "cohens_d", "Feature1_mean", "Feature2_mean")
if (calculate_corrvalues) {
spearman_summarytable <- do.call(rbind, spearman_statoutlist)
colnames(spearman_summarytable) <- c("Cohort", "Feature", "spearman_pval", "spearman_rval")
} else {spearman_summarytable <- NULL}
return(list(wilcox_summarytable = wilcox_summarytable, spearman_summarytable = spearman_summarytable))
# eigenrank_summarytable <- do.call(rbind, eigenranklist)
# eigenrank_summarytable[,"eigengene"] <- gsub("\\..*", "", rownames(eigenrank_summarytable))
# eigenrank_summarytable <- eigenrank_summarytable[order(eigenrank_summarytable[,"Group"], eigenrank_summarytable[,"Eigen_Score_Rank"], decreasing = TRUE),]
#
# # Write out the results
# write.table(wilcox_summarytable, paste0(COIbpoutpath, COItab_label,"_wilcox_summary_table.csv"),
# sep = ",", col.names = TRUE, row.names = FALSE)
# write.table(spearman_summarytable, paste0(COIbpoutpath, COItab_label, "_spearman_summary_table.csv"),
# sep = ",", col.names = TRUE, row.names = FALSE)
# write.table(eigenrank_summarytable, paste0(COIbpoutpath, COItab_label, "_eigenrank_summary_table.csv"),
# sep = ",", col.names = TRUE, row.names = FALSE)
#
# # bptablist[[params_num]] <- bptab
#
# ALL_wilcox_statoutlist[[COItabnum]] <- wilcox_summarytable
# names(ALL_wilcox_statoutlist[COItabnum]) <- COItab_label
# ALL_spearman_statoutlist[[COItabnum]] <- spearman_summarytable
# names(ALL_spearman_statoutlist[COItabnum]) <- COItab_label
#
# }
# ALL_wilcox_sumarytable <- do.call(rbind, ALL_wilcox_statoutlist)
# ALL_spearman_sumarytable <- do.call(rbind, ALL_spearman_statoutlist)
}
# --------------------------------- cluster vs event heatmap ---------------------------------
# what do i want to control - selected_cluster_table, events (EOI), cohorts (COI), outfilepath, bioreptable (indexed with EOI and COI)
# but i need new E and C ADDED TO the bioreptable already
cluster_vs_event_kmanalysis_summary_heatmap <- function(selected_cluster_table, COIref_tablist, survivalplot_outfilepath, bioreptable_waddons,
eventpvalcutoff, return_output_tables = FALSE, EOI = NULL, ...) {
## Grab EOI from our bioreptable
if (!is.null(EOI)) {EOI <- gsub("^C_", "", colnames(bioreptable_waddons)[grepl("^C_", colnames(bioreptable_waddons))])}
EOIcols <- apply(expand.grid(c("T_", "C_"), EOI, stringsAsFactors = FALSE), 1, paste, collapse = "")
# For each cluster label - lets run this analysis
expanded_nmflabeltable <- data.frame(make_comparison_columns(selected_cluster_table[,2,drop=FALSE]))
# Turn our expanded nmfcluster table back into a list with each column as an entry:
expanded_nmflabeltable_list <- lapply(expanded_nmflabeltable[,!colnames(expanded_nmflabeltable) %in% "PATNUM"], function(x)
data.frame(x, row.names = rownames(expanded_nmflabeltable[,!colnames(expanded_nmflabeltable) %in% "PATNUM"])))
for (clusterlabelnum in seq_len(length(colnames(expanded_nmflabeltable[,!colnames(expanded_nmflabeltable) %in% "PATNUM"])))){
colnames(expanded_nmflabeltable_list[[clusterlabelnum]]) <-
colnames(expanded_nmflabeltable[,!colnames(expanded_nmflabeltable) %in% "PATNUM"])[clusterlabelnum]
}
## Ok - so we want to iterate over every GOI, and every event, and see what comes out
survival_fulltable <- Reduce(function(dtf1, dtf2) merge(dtf1, dtf2, by = "PATNUM", all = TRUE, sort = FALSE), list(
bioreptable_waddons, cbind.data.frame(PATNUM = rownames(expanded_nmflabeltable), expanded_nmflabeltable)
))
write.table(survival_fulltable, paste0(survivalplot_outfilepath, "full_survival_intable.csv"), sep = ",", col.names = NA, row.names = TRUE)
## COI tab list - the categories to compare against
COItablist <- c(COIref_tablist, expanded_nmflabeltable_list)
fullpvaloutlist <- fullcumhazoutlist <- fullcohortNtablelist <- list()
clusterplotCOI <- c()
for (COInum in seq_len(length(COItablist))) {
## Select COI
COIsel <- COItablist[[COInum]]
COIlabel <- names(COItablist)[COInum]
# Create the intable with events and the specific category of interest
survival_intable <- merge(survival_fulltable[,c("PATNUM", EOIcols)], cbind(PATNUM = rownames(COIsel), COIsel), by = "PATNUM")
colnames(survival_intable)[ncol(survival_intable)] <- COIlabel
survpvallist <- survHRlist <- cohortNtablelist <- list()
for (eventnum in seq_len(length(EOI))) {
## Select event
eventsel <- EOI[eventnum]
## Create the subsurvivaltab
survivaldata <- na.omit(data.frame(survival_intable[,c(paste0(c("T_", "C_"), eventsel), COIlabel, "PATNUM")]))
rownames(survivaldata) <- survivaldata[,"PATNUM"]
survivaldata <- survivaldata[,!colnames(survivaldata) %in% "PATNUM"]
survivaldata <- survivaldata[!survivaldata[,3] %in% c(NA, "") &
!survivaldata[,2] %in% c(NA, "NotAvailable") & !survivaldata[,1] %in% c(NA, "NotAvailable"),]
survivaldata[,1] <- as.numeric(survivaldata[,1])
survivaldata[,2] <- as.numeric(survivaldata[,2])
## Ok, for the competing events - we have to clean those out cause it screws with the analysis - just remove I guess?
survivaldata <- survivaldata[!survivaldata[,grepl("^C_", colnames(survivaldata))] %in% 2,]
## Need to properly factorize our cohort data
if (COIlabel %in% c("IMGDEGIS")) {
survivaldata[,3] <- factor(survivaldata[,3], levels = c("None", "Mild", "Moderate", "Severe"))
} else if (COIlabel %in% c("IMGDEGIS_01_2_3")) {
survivaldata[,3] <- factor(survivaldata[,3], levels = c("NoneMild", "Moderate", "Severe"))
} else if (COIlabel %in% c("IMGDEGIS_01_3")) {
survivaldata[,3] <- factor(survivaldata[,3], levels = c("NoneMild", "Severe"))
} else if (COIlabel %in% c("CTNDV50")) {
survivaldata[,3] <- factor(survivaldata[,3], levels = c("Non-evaluable", "1", "2", "3"))
} else if (COIlabel %in% c("CTNDV50_123_clean")) {
survivaldata[,3] <- factor(survivaldata[,3], levels = c("1", "2", "3"))
} else if (COIlabel %in% c("CTNDV50_13_clean")) {
survivaldata[,3] <- factor(survivaldata[,3], levels = c("1", "3"))
} else if (COIlabel %in% c("CKD")) {
survivaldata[,3] <- factor(survivaldata[,3], levels = c("No", "Yes"))
} else if (COIlabel %in% c("highlowage")) {
survivaldata[,3] <- factor(survivaldata[,3], levels = c("AGE_RAND_low", "AGE_RAND_highQ3"))
} else if (COIlabel %in% c("rna_4cluster_w3AB")) {
survivaldata[,3] <- factor(survivaldata[,3],
levels = c("nmf_cluster_1", "nmf_cluster_2", "nmf_cluster_3A", "nmf_cluster_3B", "nmf_cluster_4"))
clusterplotCOI <- c(clusterplotCOI, "rna_4cluster_w3AB_nmf_cluster_1", "rna_4cluster_w3AB_nmf_cluster_2",
"rna_4cluster_w3AB_nmf_cluster_3A", "rna_4cluster_w3AB_nmf_cluster_3B", "rna_4cluster_w3AB_nmf_cluster_4")
} else if (COIlabel %in% c("rna_4cluster")) {
survivaldata[,3] <- factor(survivaldata[,3],
levels = c("nmf_cluster_1", "nmf_cluster_2", "nmf_cluster_3", "nmf_cluster_4"))
clusterplotCOI <- c(clusterplotCOI, "rna_4cluster_nmf_cluster_1", "rna_4cluster_nmf_cluster_2",
"rna_4cluster_nmf_cluster_3", "rna_4cluster_nmf_cluster_4")
} else if (COIlabel %in% c("meth_4cluster")) {
survivaldata[,3] <- factor(survivaldata[,3],
levels = c("meth_4cluster_1", "meth_4cluster_2", "meth_4cluster_3", "meth_4cluster_4"))
clusterplotCOI <- c(clusterplotCOI, "meth_4cluster_meth_4cluster_1", "meth_4cluster_meth_4cluster_2",
"meth_4cluster_meth_4cluster_3", "meth_4cluster_meth_4cluster_4")
} else if (COIlabel %in% c("meth_3cluster")) {
survivaldata[,3] <- factor(survivaldata[,3],
levels = c("meth_4cluster_1", "meth_4cluster_2", "meth_4cluster_3"))
clusterplotCOI <- c(clusterplotCOI, "meth_4cluster_meth_4cluster_1", "meth_4cluster_meth_4cluster_2",
"meth_4cluster_meth_4cluster_3")
} else {
cohortlabels <- unique(survivaldata[,3])
survivaldata[,3] <- factor(survivaldata[,3], levels = c(as.character(cohortlabels[grepl("not_", cohortlabels)]),
as.character(cohortlabels[!grepl("not_", cohortlabels)])))
}
# At this point - lets also output an N table
cohortNtablelist[[eventnum]] <- cbind(data.frame(table(survivaldata[,3])), COIlabel)
names(cohortNtablelist)[eventnum] <- eventsel
## ADDING IN HERE A FAILSAFE - 2023-04-06
if (length(table(survivaldata[,3])) < 2 | length(table(survivaldata[,3])) < 2) {
outsurvtable <- data.frame(NA)
outsurvplot <- NULL
outsurvpvalue <- data.frame(variable = "Cohort", pval = 1, method = "Log-rank", pval.txt = 1)
} else {
## Run the analysis
survivalanalysisout <- suppressWarnings(create_survival_plot(survivaldata = survivaldata, timebreakparam = NULL, ylimitparam = c(0.25,1)))
outsurvtable <- survivalanalysisout$outsurvtable
outsurvplot <- survivalanalysisout$outsurvplot
outsurvpvalue <- survivalanalysisout$outsurvpvalue
}
## ADDING IN HERE A FAILSAGE - 2023-04-06
## Save out the pvalue of the log-rank test
survpvallist[[eventnum]] <- outsurvpvalue[,"pval"]
names(survpvallist)[eventnum] <- eventsel
# Ok, I think we need to return the HR as well for coxph to get some kind of effect size for this analysis
outcoxphobject <- survivalanalysisout$outcoxphobject
## Put a hack in here to get the orientation correct. If theres only one comp, then coerce to a 1x3 dataframe:
coxtempout <- summary(outcoxphobject)[["conf.int"]][,c("exp(coef)", "lower .95", "upper .95")]
if(is.null(dim(coxtempout))){
coxtempout <- t(data.frame(coxtempout))
rownames(coxtempout) <- levels(survivaldata[,3])[2] ## I can do this because I know the first level is always the ref and I set this earlier above ^^
}
hrvalue <- cbind(coxtempout, Event = eventsel, Cohort = COIlabel)
## Save out the coxph HR of the coxph test
survHRlist[[eventnum]] <- hrvalue
names(survHRlist)[eventnum] <- eventsel
## Write out the plot and table
outsubdir <- paste0(survivalplot_outfilepath, COIlabel, "/", eventsel, "/")
dir.create(outsubdir, showWarnings = FALSE, recursive = TRUE)
write.table(outsurvtable, paste0(outsubdir, COIlabel, "_", eventsel, "_survival_stat_table.csv"),
sep = ",", col.names = TRUE, row.names = FALSE)
pdf(paste0(outsubdir, COIlabel, "_", eventsel, "_survival_plot.pdf"), width = 8, height = 5, onefile=FALSE)
suppressWarnings(print(outsurvplot)) # warn suppress for when we cut off the stray point below 0.25
junk <- dev.off()
}
survpvaltab <- do.call(rbind, survpvallist)
colnames(survpvaltab) <- paste0(COIlabel, "_pval")
survhazardtab <- do.call(rbind, survHRlist)
colnames(survhazardtab) <- paste0(COIlabel, "_", colnames(survhazardtab))
cohortNtable <- do.call(rbind, cohortNtablelist)
colnames(cohortNtable) <- c("Cohort", "Number", "COI")
fullpvaloutlist[[COInum]] <- survpvaltab
names(fullpvaloutlist[COInum]) <- paste0(COIlabel)
fullcumhazoutlist[[COInum]] <- survhazardtab
names(fullcumhazoutlist)[COInum] <- paste0(COIlabel)
fullcohortNtablelist[[COInum]] <- cohortNtable
names(fullcohortNtablelist)[COInum] <- paste0(COIlabel)
}
fullpvalouttable <- do.call(cbind, fullpvaloutlist)
write.table(fullpvalouttable, paste0(survivalplot_outfilepath, "full_survival_pval_table.csv"), sep = ",", col.names = NA, row.names = TRUE)
fullcumhazouttable <- data.frame(do.call(rbind, fullcumhazoutlist))
colnames(fullcumhazouttable) <- c("HR", "lower_CI", "upper_CI", "Event", "Cohort")
fullcumhazouttable[,c("HR", "lower_CI", "upper_CI")] <- apply(fullcumhazouttable[,c("HR", "lower_CI", "upper_CI")], 2, function(x)
as.numeric(as.character(x)))
write.table(fullcumhazouttable, paste0(survivalplot_outfilepath, "full_survival_cumhaz_table.csv"), sep = ",", col.names = NA, row.names = TRUE)
fullcohortNouttable <- do.call(rbind, fullcohortNtablelist)
write.table(fullcohortNouttable, paste0(survivalplot_outfilepath, "full_survival_cohortN_table.csv"), sep = ",", col.names = NA, row.names = TRUE)
## Summary heatmap of the pvals
fullstatouttable <- fullpvalouttable
## Turn the event outcome into a heatmap
eventpvalcutoff <- eventpvalcutoff
outeventpvaltab <- fullstatouttable[,paste0(plotCOI, "_pval")]
## Create the initial maptab
maptab <- data.frame(outeventpvaltab)
EOIvec <- colnames(outeventpvaltab)
## Add in geneordering
geneorder <- rownames(outeventpvaltab[order(outeventpvaltab[,1], decreasing = FALSE),])
## Create HR table for directionality
hazardmaptabtemp <- dcast(data.frame(fullcumhazouttable[fullcumhazouttable[,"Cohort"] %in% plotCOI, c("Event", "Cohort", "HR")]),
Event ~ Cohort, value.var = "HR")
rownames(hazardmaptabtemp) <- hazardmaptabtemp[,1]
hazardmaptabtemp <- hazardmaptabtemp[rownames(maptab), gsub("_pval", "", colnames(maptab))]
hazardmaptab <- apply(hazardmaptabtemp, 2, as.numeric)
rownames(hazardmaptab) <- hazardmaptabtemp[,1]
hazardsigntab <- ifelse(hazardmaptab > 1, 1, -1)
maptab <- maptab * hazardsigntab
heatmapcolorparam = colorRamp2(c(-1, -eventpvalcutoff - 0.0001, -eventpvalcutoff, -0.0001, -1e-100, 0,
1e-100, 0.0001, eventpvalcutoff, eventpvalcutoff + 0.0001, 1),
c("grey", "grey", "#bcb2fd", "#11007d", "#11007d", "white",
"#7d0000", "#7d0000", "#ffb2b2", "grey", "grey"))
# "#bcb2fd"
# old light red "#fd9999"
# heatmapcolorLEGEND = colorRamp2(c(-eventpvalcutoff, 0, eventpvalcutoff), c("blue", "white", "red"))
ht1 = Heatmap(as.matrix(maptab),