-
Notifications
You must be signed in to change notification settings - Fork 19
/
server.R
2092 lines (1899 loc) · 91.2 KB
/
server.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
#' server.R for Gliovis
# This file is part of GlioVis
# Copyright (C) Massimo Squatrito
#
# GlioVis is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# GlioVis is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, see <http://www.gnu.org/licenses/>.
`%notin%` <- Negate('%in%')
shinyServer(
function(input, output, session) {
options(shiny.maxRequestSize=200*1024^2)
output$adult_table <- DT::renderDataTable({
adult_table <- readxl::read_excel("data/adult.xlsx")
sketch <- htmltools::withTags(table(
class = 'compact nowrap',
style = 'font-size: 13px; line-height: 10px;',
thead(
tr(
th(rowspan = 2, "Dataset"),
th(rowspan = 2, "Data type"),
th(colspan = 3, style = 'font-style:italic;','Samples'),
th(colspan = 7, style = 'font-style:italic;','Plots')
),
tr(
lapply(c("Non-tumor", "Low-grade", "GBM", "Histology", "Grade",
"Copy Number", "Subtype", "CIMP", "Recurrence", "Survival"),th)
)
)
)
)
datatable(adult_table,escape = FALSE,container = sketch, rownames = F,
selection = "none", options = list(pageLength = 30, dom = 't'))
})
output$pediatric_table <- DT::renderDataTable({
pediatric_table <- readxl::read_excel("data/pediatric.xlsx")
sketch <- htmltools::withTags(table(
class = 'compact nowrap',
style = 'font-size: 13px; line-height: 10px;',
thead(
tr(
th(rowspan = 2, "Dataset"),
th(rowspan = 2, "Data type"),
th(colspan = 2, style = 'font-style:italic;','Samples'),
th(colspan = 5, style = 'font-style:italic;','Plots')
),
tr(
lapply(c("Non-tumor", "Tumor","Histology", "Grade","Subtype", "Recurrence", "Survival"),th)
)
)
)
)
datatable(pediatric_table,escape = FALSE, container = sketch, rownames = F,
selection = "none", options = list(pageLength = 30, dom = 't'))
})
dataset_type <- reactive({
switch(input$datasetType,
"Adult" = datasets$adult_datasets,
"Pediatric" = datasets$pediatric_datasets)
})
observe({
updateSelectizeInput(session, inputId = "dataset", choices = dataset_type(), selected = dataset_type()[1], server = TRUE)
})
# #' Return the requested dataset
# dataset_input <- reactive({
# req(input$dataset)
# file <- paste0("data/datasets/",input$dataset,".Rds")
# data <- readRDS(file)
# })
#' Return the requested dataset
dataset_input <- reactive({
eval(parse(text = input$dataset))
})
#' plotType
plotList <- reactive({
dataset_input()[["plotType"]]
})
#' Expression data
exprs <- reactive({
if(input$dataset == "TCGA_GBM") {
switch(input$microarray_platform,
"HG-U133A" = dataset_input()[["expr"]],
"Agilent-4502A" =dataset_input()[["agilent"]],
"RNA-Seq" = dataset_input()[["rseq"]]
)
} else {
dataset_input()[["expr"]]
}
})
#' Phenotype data
pDatas <- reactive({
dataset_input()[["pData"]]
})
#' CNA data
cnas <- reactive({
dataset_input()[["cna"]]
})
#' RPPA data
rppas <- reactive({
dataset_input()[["rppa"]]
})
#' Text matching with the gene names list
updateSelectizeInput(session, inputId = "gene", choices = genes$Gene, server = TRUE)
updateSelectizeInput(session, inputId = "gene2", choices = genes$Gene, server = TRUE)
updateSelectizeInput(session, inputId = "corrGene", choices = genes$Gene, server = TRUE)
observeEvent(input$gene,{
updateSelectizeInput(session, inputId = "mutGene", choices = genes$Gene, selected = input$gene, server = TRUE)
})
#' Required for the conditional panel 'corrMany' to work correctly
observeEvent(input$tab1 != 3,{
updateTabsetPanel(session, inputId = "tabCorr", selected = "corrTwo")
})
observeEvent(input$tabTools != "DeconvoluteMe",{
updateCheckboxInput(session, inputId = "deconvPData", value = FALSE)
})
#' When switching datasets, if the selected plot is not available it will choose the first plot of the list
plot_selected <- reactive({
if (input$plotTypeSel %in% plotList()){
input$plotTypeSel
} else {
NULL
}
})
#' Return the names of the available user-defined plots
plot_user_selection <- reactive({
# Exclude the pre-defeined plots and numeric variabe
dropit <- c("Sample","Histology","Grade","Recurrence","Subtype", "CIMP_status", "survival",
"status", "Age", "ID","Patient_ID","Sample_ID", "Matching.sample", "Therapy_Class","title","tumor_name")
data <- pDatas()[,names(pDatas()) %notin% dropit, drop = FALSE]
n <- names(data)
n
})
#' When switching datasets, if the selected plot is not available it will choose the first plot of the list
plot_user_selected <- reactive({
if (input$plotTypeUserSel %in% plot_user_selection()){
input$plotTypeUserSel
} else {
NULL
}
})
plot_type <- reactive({
if (input$plotType == "Pre-defined"){
plot_selected()
} else if (input$plotType == "User-defined") {
plot_user_selected()
}
})
#' Change the plot type available for a specific dataset
observe({
updateSelectizeInput(session, inputId = "plotTypeSel", choices = plotList(), selected = plot_selected())
updateSelectizeInput(session, inputId = "plotTypeUserSel", choices = plot_user_selection(), selected = plot_user_selected())
})
# Caption with gene and dataset
output$caption <- renderText({
req(input$gene)
title <- paste(input$gene, "in", input$dataset, "dataset")
})
#' Return the available histology, to be used in the updateSelectInput
histo <- reactive({
levels(exprs()[,"Histology"])
})
#' Return the available subtype, to be used in the updateSelectInput
subtype <- reactive({
req(input$dataset)
if (input$histology == "All"){
df <- exprs()
subtype <- levels(df$Subtype)
} else{
df <- subset(exprs(), Histology == input$histology)
subtype <- intersect(levels(df$Subtype),df$Subtype)
}
subtype
})
#' When switching datasets if the selected histo is not available it will choose "All"
histo_selected <- reactive({
if(input$dataset == "TCGA_GBM" & input$tab1 == 2){
histo <- "GBM"
} else if(input$histology %in% c("All", histo())){
histo <- input$histology
} else {
histo <- "All"
}
histo
})
#' When switching datasets if the selected subtype is not available it will choose "All"
subtype_selected <- reactive({
if(input$subtype %in% c("All", subtype())){
input$subtype
} else {
"All"
}
})
observe({
updateSelectInput(session, inputId = "histology", choices = c("All", histo()), selected = histo_selected())
updateSelectInput(session, inputId = "subtype", choices = c("All", subtype()), selected = subtype_selected())
})
#' Generate a dataframe with the data to plot
data <- reactive({
# Trying to avoid an error when switching datasets in case the plotType is not available.
req(c(plot_selected(),plot_user_selected()) %in% c(plotList(),plot_user_selection()))
# req(plot_user_selected() %in% plot_user_selection())
validate(
need(input$gene != "", "Please, enter a gene name in the panel on the left")%then%
# Not all genes are available for all the dataset
need(input$gene %in% names(exprs()),"Gene not available for this dataset")
)
# mRNA <- exprs()[ ,input$gene]
# if (input$scale) {
# mRNA <- scale(mRNA)
# }
# data <- cbind(mRNA, exprs()[,2:6]) # To combine with pData
# data <- cbind(data, pDatas()[,!names(pDatas()) %in% names(data)]) # To combine with more pData for the report
# if (input$dataset %in% c("TCGA_GBM", "TCGA_LGG", "TCGA_GBMLGG")) {
# if(input$gene %in% names(cnas())){
# Copy_number <- cnas()[ ,input$gene]
# Copy_number <- factor(Copy_number, levels = c(-2:2), labels = c("Homdel", "Hetloss", "Diploid", "Gain", "Amp"))
# Copy_number <- droplevels(Copy_number)
# } else {
# Copy_number <- NA # Some genes don't have copy numbers data
# }
# data <- cbind(Copy_number,data)
# }
data <- exprs()[ ,c("Sample", input$gene)]
names(data)[2] <- "mRNA"
if (input$scale) {
data$mRNA <- as.numeric(scale(data$mRNA))
}
data <- merge(data, pDatas(), by = "Sample") # To combine with pData
# Temporary fix: when I changed from `cbind` to `merge` I forgot to include
# the Subtype column (present in exprs() but not in pDatas() of most GBM datasets)
if(!"Subtype" %in% names(data)){
sub <- exprs()[ ,c("Sample", "Subtype")]
data <- merge(data, sub, by = "Sample")
}
if (input$dataset %in% c("TCGA_GBM", "TCGA_LGG", "TCGA_GBMLGG")) {
if (input$gene %in% names(cnas())) {
cna <- rownames_to_column(cnas(), var = "Sample")
cna <- cna[ ,c("Sample", input$gene)]
names(cna)[2] <- "Copy_number"
cna <- cna %>%
# rename("Copy_number" = !!names(.[2]) %>%
mutate(Copy_number = factor(Copy_number, levels = c(-2:2), labels = c("Homdel", "Hetloss", "Diploid", "Gain", "Amp")),
Copy_number = droplevels(Copy_number))
data <- merge(cna, data, by = "Sample", all = TRUE)
} else {
data$Copy_number <- NA # Some genes don't have copy numbers data
}
}
if(input$dataset == "CGGA"){
if(input$primaryCgga != "All"){
data <- subset(data, Recurrence == input$primaryCgga)
} else {
data
}
}
rownames(data) <- data$Sample
data <- data[complete.cases(data[,"mRNA"]),] # Aiglent TCGA_GBM data doesn't have all the observations
data
})
#' Data for the box plot
plot_data <- reactive({
validate(
need(!all(is.na(data()[ ,plot_type()])),"Sorry,no gene data available for this group")
)
data <- data()
data <- subset(data, !is.na(data[ ,plot_type()]))
})
#' Filtered data for the box plot
filter_plot_data <- reactive({
if (input$removeMe) {
req(input$removeGp %in% levels(plot_data()[ ,plot_type()])) #To silence an error thrown by the stat analysis
data <- plot_data()
data <- subset(data, data[ ,plot_type()] %in% input$removeGp)
data[ ,plot_type()] <- factor(data[ ,plot_type()],levels = input$removeGp)
} else {
data <- plot_data()
}
data
})
#' Select input for groups to add/exclude
output$removeGp <- renderUI({
groups <- levels(plot_data()[ ,plot_type()])
selectizeInput(inputId = "removeGp", label = "", choices = groups, selected = groups, multiple = TRUE,
options = list(plugins = list('remove_button','drag_drop')))
})
#' Reset input$removeMe when plot_data() changes
observeEvent(plot_data(), {
updateCheckboxInput(session, inputId = "removeMe", value = FALSE)
})
#' Populate Xaxis labels
observe({
updateTextInput(session, inputId = "myXlab",value = paste0("\n",plot_type()))
})
# Tukey plot active only when tukey stat data are shown
observeEvent(!input$tukeyHSD, {
updateCheckboxInput(session, inputId = "tukeyPlot", value = FALSE)
})
#' Reactive function to generate the box plots
#' chekck for tydy eval strategies https://aosmith.rbind.io/2018/08/20/automating-exploratory-plots/
box_Plot <- reactive({
data <- filter_plot_data()
xlabel <- paste("\n", input$myXlab)
ylabel <- paste(input$myYlab,"\n")
fillBox <- NULL
col <- input$colorP
shape <- input$shapeP
theme <- theme(axis.text.x = element_text(size = input$axis_text_size, angle = input$xaxisLabelAngle, hjust = ifelse(input$xaxisLabelAngle == 0,0.5,1)),
axis.text.y = element_text(size = input$axis_text_size),
axis.title.x = element_text(size = input$axis_title_size),
axis.title.y = element_text(size = input$axis_title_size))
if (input$colBox) fillBox <- plot_type()
if(input$colorP == "None") col <- NULL
if(input$shapeP == "None") shape <- NULL
if (input$bw) theme <- theme_bw () + theme
p <- ggplot(data, mapping=aes_string(x=plot_type(), y = "mRNA")) +
geom_boxplot(aes_string(fill = fillBox), outlier.size = 0, outlier.stroke = 0) +
geom_jitter(position = position_jitter(width = .25), mapping = aes_string(colour = col, shape = shape),
size = input$point_size, alpha = input$alpha) +
ylab(ylabel) + xlab(xlabel) + theme
if (input$tukeyPlot) {
t <- tukey() %>%
mutate(comparison = row.names(.)) %>%
ggplot(aes(reorder(comparison, diff), diff, ymin = lwr, ymax= upr, colour = Significance)) +
geom_point() + geom_errorbar(width = 0.25) + ylab("\nDifferences in mean levels") + xlab("") +
geom_hline(yintercept = 0, colour="darkgray", linetype = "longdash") + coord_flip() +
scale_x_discrete(labels = abbreviate) + theme
p <- grid.arrange(p, t, ncol=2, widths = c(3,2))
}
#
# if(input$dataset == "CGGA"){
# p <- p + facet_grid(~Recurrence, scales = "free_x")
# }
return(p)
})
#' Table with the data used for the plot
output$filterDataTable <- DT::renderDataTable({
columns <- intersect(c("Sample", plot_type(),input$colorP,input$shapeP,"mRNA"),names(filter_plot_data()))
data <- filter_plot_data()[,columns]
data_table(data)
},server = FALSE)
observe({
data <- .rmNA(filter_plot_data())
colnames <- names(data)[!sapply(data, is.numeric)] # remove muneric categories
colnames <- colnames[colnames %notin% "Sample"]
# Create the selectInput for the different pData categories
updateSelectInput(session, "colorP", "Color by:", choices = c("None",colnames), selected = "None")
updateSelectInput(session, "shapeP", "Shape by:", choices = c("None",colnames), selected = "None")
})
box_width <- reactive({
if(input$tukeyPlot)
input$plot_width* 2 else
input$plot_width
})
#' Create the selected plot
output$plot <- renderPlot({
# To avoid an error when switching datasets in case the colStrip is not available.
data <- .rmNA(filter_plot_data())
colnames <- names(data)[names(data) %notin% c("mRNA","Sample","status","survival")]
req(input$colorP %in% c("None", colnames) & input$shapeP %in% c("None", colnames))
box_Plot()
}, width = box_width, height = function()input$plot_height)
#' Data for the statistic
observe({filter_plot_data()})
stat_data <- reactive({
mRNA <- filter_plot_data()[ ,"mRNA"]
group <- filter_plot_data()[ ,plot_type()]
data <- data.frame(mRNA, group)
data
})
#' Summary statistic
output$summary <- renderTable({
data <- stat_data()
stat <- data %>%
group_by(group) %>%
summarise(Sample_count = paste0(n()," (", round(n()*100/dim(data)[1], 2), "%)" ), # prop.table
median = median(mRNA, na.rm=T), mad = mad(mRNA, na.rm=T), mean = mean(mRNA, na.rm=T),
sd = sd(mRNA, na.rm=T)) %>%
data.frame()
row.names(stat) <- stat$group
tot <- data %>%
summarise(Sample_count = n(), median = median(mRNA, na.rm=T),
mad = mad(mRNA, na.rm=T), mean = mean(mRNA, na.rm=T), sd = sd(mRNA, na.rm=T))
stat <- stat[,-1]
stat <- rbind(stat,TOTAL = tot)
stat
}, align='rrrrrr',rownames =TRUE, striped = TRUE)
#' Tukey post-hoc test, to combine it with the boxplot and to render in a table
tukey <- reactive({
validate(
need(nlevels(stat_data()$group)>1,message = "There is only one category, group comparison cannot be performed")
)
data <- stat_data()
tukey <- data.frame(TukeyHSD(aov(mRNA ~ group, data = data))[[1]])
tukey$Significance <- as.factor(weights::starmaker(tukey$p.adj, p.levels = c(.001, .01, .05, 1), symbols=c("***", "**", "*", "ns")))
tukey <- tukey[order(tukey$diff, decreasing = TRUE), ]
tukey
})
#' Render tukey
output$tukeyTest <- renderTable({
tukey()
}, digits = c(2,2,2,-1,2), rownames =TRUE, striped = TRUE)
#' Pairwise t test
output$pairwiseTtest <- renderTable({
validate(
need(nlevels(stat_data()$group)>1,message = "There is only one category, group comparison cannot be performed")
)
data <- stat_data()
pttest <- pairwise.t.test(data$mRNA, data$group, na.rm= TRUE, p.adj = "bonferroni", paired = FALSE)
pttest$p.value
}, digits = -1,rownames =TRUE)
#' Get the selected download file type.
download_plot_file_type <- reactive({
input$downloadPlotFileType
})
observe({
plotFileType <- input$downloadPlotFileType
plotFileTypePDF <- plotFileType == "pdf"
plotUnit <- ifelse(plotFileTypePDF, "inches", "pixels")
plotUnitDef <- ifelse(plotFileTypePDF, 7, 600)
plotUnitMin <- ifelse(plotFileTypePDF, 1, 100)
plotUnitMax <- ifelse(plotFileTypePDF, 12, 2000)
plotUnitStep <- ifelse(plotFileTypePDF, 0.1, 50)
updateNumericInput(
session,
inputId = "downloadPlotHeight",
label = sprintf("Height (%s)", plotUnit),
value = plotUnitDef, min = plotUnitMin, max = plotUnitMax, step = plotUnitStep)
updateNumericInput(
session,
inputId = "downloadPlotWidth",
label = sprintf("Width (%s)", plotUnit),
value = plotUnitDef, min = plotUnitMin, max = plotUnitMax, step = plotUnitStep)
})
#' Get the download dimensions.
download_plot_height <- reactive({
input$downloadPlotHeight
})
download_plot_width <- reactive({
input$downloadPlotWidth
})
download_plot_res <- reactive({
input$downloadPlotRes
})
#' Download the Plot
output$downloadPlot <- downloadHandler(
filename = function() {
paste0(Sys.Date(), "_", input$gene, "_", input$dataset, "_", input$plotTypeSel,
".", download_plot_file_type())
},
# The argument content below takes filename as a function and returns what's printed to it.
content = function(file) {
# Gets the name of the function to use from the downloadFileType reactive element.
plotFunction <- match.fun(download_plot_file_type())
plotFunction(file, width = download_plot_width(), height = download_plot_height())
if(download_plot_file_type()!="pdf"){
plotFunction(file, width = download_plot_width(), height = download_plot_height(),res = download_plot_res())
}
if (input$tukeyPlot) {
grid.draw(box_Plot())
} else {
print(box_Plot())
}
dev.off()
}
)
#' Observers for the conditonal panels to work in the proper way
observeEvent(input$histology != "GBM", {
updateRadioButtons(session, "primarySurv", selected = "All")
updateRadioButtons(session, "mgmtSurv", selected = "All")
})
observeEvent(!input$dataset %in% c("TCGA_GBM","Murat"), {
updateRadioButtons(session, "mgmtSurv", selected = "All")
})
observeEvent(c(input$subtype != "All", input$tabSurv != 'km'), {
updateCheckboxInput(session, "allSubSurv", value = FALSE)
})
#' Select gender
output$genderSurv <- renderUI({
req("Gender" %in% names(data()))
selectInput(inputId ="genderSurv", label = h4("Gender:"),
choices = c("All","Female","Male"), selected = "All")
})
#' Select IDH status
#' I couldn find a way to use the renderUI and the observeEvent to work correctly from the server side
# output$idhSurv <- renderUI({
# req(input$dataset %in% c("CGGA","TCGA_GBM", "TCGA_LGG", "TCGA_GBMLGG","Gorovets","Gravendeel",
# "POLA_Network","Kamoun"))
# selectInput(inputId ="idhSurv", label = h4("IDH status:"),
# choices = c("All","Wild_type","Mutant"), selected = "All")
# })
#
observeEvent(!input$dataset %in% c("CGGA","TCGA_GBM", "TCGA_LGG", "TCGA_GBMLGG","Gorovets","Gravendeel",
"POLA_Network","Kamoun"), {
updateSelectInput(session, "idhSurv", selected = "All")
})
#' Select CIMP status
# output$gcimpSurv <- renderUI({
# req(input$dataset %in% c("Rembrandt","LeeY", "Phillips", "Freije","Murat","Joo", "Ducray",
# "Nutt", "Vital","Grzmil","Donson"))
# radioButtons(inputId ="gcimpSurv", label = strong("CIMP stauts:"), choices = c("All","G-CIMP","NON G-CIMP"), selected = "All", inline = T)
# })
observeEvent(!input$dataset %in% c("Rembrandt","LeeY", "Phillips", "Freije","Murat","Joo", "Ducray",
"Nutt","Grzmil","Donson"), {
updateRadioButtons(session, "gcimpSurv", selected = "All")
})
#' Extract the survival data.
surv_data <- reactive({
df <- data()
df <- subset(df, !is.na(df$status))
df <- df[ ,names(df) %in% c("Sample", "Histology", "Recurrence", "Subtype", "CIMP_status",
"mRNA", "survival", "status", "Gender", "MGMT_status","IDH_status","IDH1_status",
"IDH2_status", "IDH.status")]
if(input$dataset %in% c("CGGA","TCGA_GBM", "TCGA_GBMLGG","Gorovets","Gravendeel","POLA_Network","Kamoun")){
# df <- rename(df, IDH_status = starts_with("IDH"))
names(df)[grepl("IDH", names(df))] <- "IDH_status"
df$IDH_status <- ifelse(df$IDH_status %in% c("Wild-type","Wildtype","Wild_type","WT","IDHwt"), "Wild_type",
ifelse(df$IDH_status %in% c("Mutant","Mut","IDHmut-codel","IDHmut-non-codel"),"Mutant",df$IDH_status))
} else if(input$dataset == "TCGA_LGG"){
# TCGA_LGG has both IDH1 and IDH2 mutation info
df$IDH_status <- ifelse(df$IDH1_status== "Mutant" | df$IDH2_status == "Mutant", "Mutant",
ifelse(df$IDH1_status== "Wild-type" | df$IDH2_status == "Wild-type","Wild_type",NA))
}
# select IDH status
if(input$idhSurv != "All"){
df <- subset(df, IDH_status == input$idhSurv)
}
# select Gender
if("Gender" %in% names(data())){
if(input$genderSurv != "All"){
df$Gender <- trimws(df$Gender, which = "right") # e.g.:"Female "
df <- subset(df, Gender == input$genderSurv)
}
}
# select Histology
if(input$histology != "All"){
df <- subset(df, Histology == input$histology)
}
# select Subtype
if (input$subtype != "All") {
df <- subset(df, Subtype == input$subtype)
}
# select G-CIMP status
if(input$gcimpSurv != "All"){
df <- subset(df, CIMP_status == input$gcimpSurv)
}
# select MGMT status
if(input$mgmtSurv != "All"){
df <- subset(df, MGMT_status == input$mgmtSurv)
}
# select primary sample
if(input$primarySurv != "All" & any(!is.na(df$Recurrence))) {
df <- subset(df, Recurrence == input$primarySurv)
}
df <- .rmNA(df)
})
#' Create a slider for the manual cutoff of the Kaplan Meier plot
mRNA_surv <- reactive({
surv_need()
req(input$histology %in% c("All", histo()))
mRNA <- surv_data()[ ,"mRNA"]
mRNA.values <- round(mRNA[!is.na(mRNA)],2)
# Generate a vector of continuos values, excluding the first an last value
mRNA.values <- sort(mRNA.values[mRNA.values != min(mRNA.values) & mRNA.values != max(mRNA.values)])
})
#' Create a rug plot with the mRNA expression value for the manual cutoff
output$boxmRNA <- renderPlot({
req(input$mInput)
mRNA <- round(mRNA_surv(),2)
q <- quantile(mRNA)
xrange <-range(mRNA)
par(mar = c(0,0,0,0))
plot(0, 0, type = "n", xlim = c(xrange[1] + 0.25, xrange[2]) , ylim = c(-0.1, + 0.1), ylab ="", xlab = "", axes = FALSE)
points(x = mRNA, y = rep(0, length(mRNA)), pch="|", col=rgb(0, 0, 0, 0.25))
# Add a red line to show which is the current cutoff.
points(x = input$mInput, y = 0, pch = "|", col="red", cex = 2.5)
points(x = q[2:4], y = rep(0,3), pch = "|", col="blue", cex = 2)
}, bg = "transparent")
#' Generate the slider for the manual cutoff
output$numericCutoff <- renderUI({
sliderInput(inputId = "mInput",label = NULL, min = min(mRNA_surv()), max = max(mRNA_surv()),
value = median(mRNA_surv()), step = 0.05, round = -2)
})
#' Requirements for all the survival plots
surv_need <- reactive({
validate(
need(input$dataset %notin% datasets$no_surv_dataset, "Sorry, no survival data are available for this dataset")%then%
need(input$histology != "Non-tumor","Sorry, no survival data are available for this group")%then%
need(input$gene != "", "Please, enter a gene name in the panel on the left")%then%
need(input$gene %in% names(exprs()),"Gene not available for this dataset")
)
})
#' busy indicator when switching surv tab
#' http://stackoverflow.com/questions/18237987/show-that-shiny-is-busy-or-loading-when-changing-tab-panels
output$activeTabSurv <- reactive({
return(input$tabSurv)
})
outputOptions(output, 'activeTabSurv', suspendWhenHidden=FALSE)
#' Set survival plot height
surv_plot_height <- reactive({
if(input$allSubSurv){
ifelse(length(subtype())>4, 1300, 650)
} else {
ifelse(input$riskTable, 500,325)
}
})
observeEvent(input$allSubSurv, {
updateCheckboxInput(session, inputId = "riskTable", value = FALSE)
})
#' Create a Kaplan Meier plot with cutoff based on quantiles or manual selection
output$survPlot <- renderPlot({
surv_need()
req(input$histology %in% c("All", histo()))
# Use 'try' to suppress a message throwed the first time manual cutoff is selected
if(input$allSubSurv) {
nrow <- ceiling(length(subtype())/2)
try({
# p <- list()
p <- vector("list", length(subtype()))
for (i in subtype()) {
p[[i]] <- survivalPlot(surv_data(), input$gene, group = input$histology, subtype = i, font.legend = input$surv_legend_size,
input$riskTable, cutoff = input$cutoff, numeric = input$mInput, censor = input$censor, conf.int = input$confInt)$plot
}
do.call(grid.arrange, args = list(grobs = p, nrow = 1, ncol=2))
}, silent = TRUE)
} else {
try(survivalPlot(surv_data(), input$gene, group = input$histology, subtype = input$subtype, font.legend = input$surv_legend_size,
input$riskTable, cutoff = input$cutoff, numeric = input$mInput, censor = input$censor, conf.int = input$confInt), silent = TRUE)
}
}, height = surv_plot_height, width = function(){if(!input$allSubSurv) {500} else {900}})
#' Create a table with the data used in Kaplan Meier plot
output$survDataTable <- DT::renderDataTable({
data <- surv_data()
strat <- get_cutoff(data$mRNA,input$cutoff,input$mInput)
if (input$cutoff == "quartiles"){
strat <- factor(strat,labels = c("1st quartile","2nd quartile","3rd quartile","4th quartile"))
}
data <- data.frame(data, cutoff_group = strat)
# data <- dplyr::rename(data, survival_month = survival, survival_status = status)
data_table(data)
}, server = FALSE)
#' Download the survPlot
output$downloadsurvPlot <- downloadHandler(
filename = function() {
paste0(Sys.Date(), "_", input$gene, "_", input$dataset, "_survPlot.", download_plot_file_type())
},
content = function(file) {
plotFunction <- match.fun(download_plot_file_type())
plotFunction(file, width = download_plot_width(), height = download_plot_height())
if(download_plot_file_type()!="pdf"){
plotFunction(file, width = download_plot_width(), height = download_plot_height(),res = download_plot_res())
}
if(input$allSubSurv) {
nrow <- ceiling(length(subtype())/2)
p <- list()
for (i in subtype()) {
p[[i]] <- survivalPlot(surv_data(), input$gene, group = input$histology, subtype = i, font.legend = input$surv_legend_size,
input$riskTable, cutoff = input$cutoff, numeric = input$mInput, censor = input$censor, conf.int = input$confInt)$plot
}
do.call(grid.arrange,args = list(grobs = p, nrow = nrow, ncol=2))
} else {
survivalPlot(surv_data(), input$gene, group = input$histology, subtype = input$subtype, font.legend = input$surv_legend_size,
input$riskTable, cutoff = input$cutoff, numeric = input$mInput, censor = input$censor, conf.int = input$confInt)
}
dev.off()
}
)
#' Select optimal cutpoint for Kaplan Meier plot
cutpointData <- reactive({
surv_need ()
req(input$histology %in% c("All", histo()))
df <- surv_data()
surv.cut <- surv_cutpoint(data = df, time = "survival", event = "status", variables = "mRNA")
df.cat <<- surv.cut %>% surv_categorize()
cutpoint <- list(surv.cut = surv.cut, df.cat = df.cat)
})
output$cutpointPlot <- renderPlot({
df.cat <- cutpointData()[["df.cat"]]
fit <- survfit(Surv(survival, status) ~ mRNA, data = df.cat)
p1 <- plot.surv_cutpoint(cutpointData()[["surv.cut"]])
p2 <- ggsurvplot(fit = fit, risk.table = FALSE, pval = TRUE, conf.int = input$confInt, font.legend = input$surv_legend_size,
legend = c(.75,.75), legend.title = paste("Cutoff:", round(cutpointData()[["surv.cut"]]$cutpoint,2)), surv.scale = "percent", font.x = 12, font.y = 12, font.main = 14, ylab = "Surviving",
main = "Kaplan Meier Survival Estimates", legend.labs = c(paste(input$gene, "High"), paste(input$gene, "Low")), censor = input$censor,
xlab = "Survival time (Months)")
# fit <- surv_fit(Surv(survival, status) ~ mRNA, data = df.cat)
# p1 <- plot(cutpointData()[["surv.cut"]])
# p2 <- ggsurvplot(fit = fit, risk.table = FALSE, pval = TRUE, conf.int = input$confInt, font.legend = input$surv_legend_size,
# legend = c(.75,.75), legend.title = paste("Cutoff:", round(cutpointData()[["surv.cut"]]$cutpoint,2)), surv.scale = "percent", font.x = 12, font.y = 12, font.main = 14, ylab = "Surviving",
# main = "Kaplan Meier Survival Estimates", legend.labs = c(paste(input$gene, "High"), paste(input$gene, "Low")), censor = input$censor,
# xlab = "Survival time (Months)", data = df.cat)
distribution <- ggplotGrob(p1[[1]]$distribution + theme(legend.position = "none"))
maxstat <- ggplotGrob(p1[[1]]$maxstat + theme(legend.position = "none"))
survival <- ggplotGrob(p2[[1]])
grid::grid.draw(rbind(distribution, maxstat, survival))
# grid.arrange(distribution, maxstat, survival)
})
output$cutpointDataTable <- DT::renderDataTable({
data <- cutpointData()[["df.cat"]]
# data <- dplyr::rename(data, survival_month = survival, survival_status = status) # this is throwing errors
data_table(data, rownames = T)
}, server = FALSE)
#' Subset to GBM samples for the interactive HR plot.
# surv_GBM <- reactive({
# df <- filter(surv_data(), Histology == "GBM")
# })
#' Extract the GBM expression values for the interactive HR plot.
gene_exp <- reactive({
# geneExp <- surv_GBM()[ ,"mRNA"]
geneExp <- surv_data()[ ,"mRNA"]
currentClick$stale <<- TRUE
geneExp
})
# Need a wrapper around the hrClick input so we can manage whether or
# not the click occured on the current Gene. If it occured on a previous
# gene, we'll want to mark that click as 'stale' so we don't try to use it
# later. https://gist.github.com/trestletech/5929598
currentClick <- list(click = NULL, stale = FALSE)
handleClick <- observe({
if (!is.null(input$hrClick) && !is.null(input$hrClick$x)){
currentClick$click <<- input$hrClick
currentClick$stale <<- FALSE
}
}, priority=100)
#' Generate the cutoff value for the interactive HR plot.
get_Cutoff <- reactive({
input$hrClick
gene_exp()
# See if there's been a click since the last gene change.
if (!is.null(currentClick$click) && !currentClick$stale){
return(currentClick$click$x)
}
median(gene_exp())
})
#' Extract the Hazard ratios for the input gene.
HR <- reactive ({
# HR <- getHR(surv_GBM())
HR <- getHR(surv_data())
})
#' Render a plot to show the the Hazard ratio for the gene's expression values
output$hazardPlot <- renderPlot({
# validate(need(input$dataset %notin% c("TCGA_LGG","Gorovets","POLA Network"), "Interactive HR plot currently available only for GBM samples") %then%
# need(histo_selected() == "GBM","Please select GBM samples in the 'Histology' dropdown menu") %then%
# need(input$dataset %notin% c("Grzmil","Vital"), "Sorry, too few samples to properly render the HR plot"))
validate(
need(dim(surv_data())>30 , "Sorry, too few samples to properly calculate and render the HR plot")
)
surv_need()
input$tabSurv
# Plot the hazardplot
hazardPlot(HR(), input$quantile)
# Add a vertical line to show where the current cutoff is.
abline(v = get_Cutoff(), col = 4)
}, bg = "transparent")
#' Data used to generate the HR plot
output$hazardDataTable <- DT::renderDataTable({
# validate(need(input$dataset %notin% c("TCGA_LGG","Gorovets","POLA Network"), "Interactive HR plot currently available only for GBM samples") %then%
# need(histo_selected() == "GBM","Please select GBM samples in the 'Histology' dropdown menu") %then%
# need(input$dataset %notin% c("Grzmil","Vital"), "Sorry, too few samples to properly render the HR plot"))
validate(
need(input$dataset %notin% c("Grzmil","Vital"), "Sorry, too few samples to properly render the HR plot")
)
surv_need()
data <- round(HR(),3)
names(data) <- c("mRNA", "HR", "HR.lower", "HR.upper", "n.obs.1", "n.obs.2")
data_table(data)
},server = FALSE)
#' A reactive survival formula
survival_Fml <- reactive({
# Create the groups based on which samples are above/below the cutoff
expressionGrp <- as.integer(gene_exp() < get_Cutoff())
# Create the survival object
# surv <- with(surv_GBM(), Surv(survival, status == 1))
surv <- with(surv_data(), Surv(survival, status == 1))
return(surv ~ expressionGrp)
})
#' Create a Kaplan Meier plot on the HR cutoff
output$kmPlot <- renderPlot({
validate(
need(input$dataset %notin% c("Grzmil","Vital"), "Sorry, too few samples to properly render the HR plot")
)
# req(histo_selected() == "GBM")
surv_need()
# kmPlot(data = surv_GBM(), cutoff = get_Cutoff(), surv = survival_Fml(), censor = input$censor, conf.int = input$confInt,
# font.legend = input$surv_legend_size, input$riskTable)
kmPlot(data = surv_data(), cutoff = get_Cutoff(), surv = survival_Fml(), censor = input$censor, conf.int = input$confInt,
font.legend = input$surv_legend_size, input$riskTable)
}, height = surv_plot_height)
#' Download the kmPlot
output$downloadkmPlot <- downloadHandler(
filename = function() {
paste0(Sys.Date(), "_", input$gene, "_", input$dataset, "_kmPlot.",download_plot_file_type())
},
content = function(file) {
plotFunction <- match.fun(download_plot_file_type())
plotFunction(file, width = download_plot_width(), height = download_plot_height())
if(download_plot_file_type()!="pdf"){
plotFunction(file, width = download_plot_width(), height = download_plot_height(),res = download_plot_res())
}
# kmPlot(data = surv_GBM(), cutoff = get_Cutoff(), surv = survival_Fml(), censor = input$censor, conf.int = input$confInt,
# font.legend = input$surv_legend_size, input$riskTable)
kmPlot(data = surv_data(), cutoff = get_Cutoff(), surv = survival_Fml(), censor = input$censor, conf.int = input$confInt,
font.legend = input$surv_legend_size, input$riskTable)
dev.off()
}
)
#' Generate reactive Inputs for the corrPlot to be used also to download the complete plot
color_by <- reactive({
switch(input$colorBy,
none = "none",
Histology = "Histology",
Subtype = "Subtype")
})
separate_by <- reactive({
switch(input$separateBy,
none = "none",
Histology = "Histology",
Subtype = "Subtype")
})
corr_data <- reactive({
df <- exprs()
if(input$dataset == "CGGA"){
if(input$primaryCgga != "All"){
df <- subset(df, Recurrence == input$primaryCgga)
} else {
df
}
}
if (input$histology != "All") {
df <- subset(df, Histology == input$histology)
}
if (input$subtype != "All") {
df <- subset(df, Subtype == input$subtype)
}
df
})
#' Data for the correlation plot
corr_two_data <- reactive({
validate(
need(input$gene != "", "Please, enter a gene name in the panel on the left")%then%
need(input$gene %in% names(exprs()),"Gene not available for this dataset"),
need(input$gene2 != "", "Please enter Gene 2")%then%
need(input$gene2 %in% names(exprs()),"Gene not available for this dataset"),
# Trying to avoid an error when switching datasets in case the choosen histology is not available.
need(input$histology %in% c("All",histo()), FALSE)
)
data <- corr_data()[,c("Sample", "Histology", "Subtype", input$gene, input$gene2)]
data <- data[complete.cases(data[,input$gene]),]
})
#' Generate the correlation plot
output$corrPlot <- renderPlot({
myCorggPlot(corr_two_data(), input$gene, input$gene2, colorBy = color_by(), separateBy = separate_by())
}, width = function()input$cor_plot_width, height = function()input$cor_plot_height)
#' Generate a summary of the correlation test
output$corrTest <- renderTable({
req(input$gene != input$gene2)
df <- corr_two_data()
# gene1 <- as.symbol(input$gene)
# gene2 <- as.symbol(input$gene2)
# group <- as.symbol(separate_by())
if (separate_by() != "none") {
# df <- df %>% select(group = !!group, gene1 = !!gene1, gene2 = !!gene2) # select_ is deprecated
df <- df %>% data.frame(group = .[ ,separate_by()], gene1 = .[ ,input$gene], gene2 = .[ ,input$gene2]) %>%
.[,c("group","gene1", "gene2")]
more_than_three <- df %>% group_by(group) %>% count(group) %>% filter(n>3) # to drop levels with less than 3 elements
df <- df %>% filter(group %in% more_than_three$group & group != "") %>% group_by(group)
} else {
# df <- df %>% select(gene1 = !!gene1, gene2 = !!gene2)
df <- df %>% data.frame(gene1 = .[ ,input$gene], gene2 = .[ ,input$gene2]) %>%
.[,c("gene1", "gene2")]
}
cor <- df %>% do(broom::tidy(cor.test(~ gene1 + gene2, data =., use = "complete.obs", method = tolower(input$statCorr))))
# cor <- df %>% do(broom::tidy(cor.test(quo(gene1 + gene2), data =., use = "complete.obs", method = tolower(input$statCorr))))
}, striped = TRUE)
#' Table with the data used for the correlation plot
output$corrDataTable <- DT::renderDataTable({
data <- corr_two_data()
data_table(data)
},server = FALSE)
#' Download the corrPlot
output$downloadcorrPlot <- downloadHandler(
filename = function() {
paste0(Sys.Date(), "_", input$gene, "_", input$dataset, "_corrPlot.", download_plot_file_type())
},
content = function(file) {
plotFunction <- match.fun(download_plot_file_type())
plotFunction(file, width = download_plot_width(), height = download_plot_height())
if(download_plot_file_type()!="pdf"){
plotFunction(file, width = download_plot_width(), height = download_plot_height(),res = download_plot_res())
}
myCorggPlot(corr_two_data(), input$gene, input$gene2, color_by(), separate_by())
dev.off()