-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathapp.R
1644 lines (1222 loc) · 58.8 KB
/
app.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
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# PlotsOfDifferences: Shiny app for plotting the data and DIFFERENCES (aka effect size)
# Created by Joachim Goedhart (@joachimgoedhart), first version september 2018
# Takes non-tidy, spreadsheet type data as input or tidy format
# Non-tidy data is converted into tidy format
# For tidy data the x and y variables need to be selected
# Raw data is displayed with user-defined visibility (alpha)
# Summary statistics are displayed with user-defined visibility (alpha)
# Inferential statistics (95%CI) can be added
# The 95%CI of the median is determined by resampling (bootstrap)
# The differences (effect sizes) are determined from bootstrap samples of either mean or median
# A plot and a table with stats are generated
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (C) 2018 Joachim Goedhart
# electronic mail address: j #dot# goedhart #at# uva #dot# nl
#
# This program 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.
#
# This program 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 <https://www.gnu.org/licenses/>.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# ToDo
# Implement fold-change as an effect size
##### Define dependencies ######
library(shiny)
library(plyr)
library(ggplot2)
library(tidyverse)
library(ggbeeswarm)
library(readxl)
library(DT)
library(RCurl)
library(shinycssloaders)
library(patchwork)
library(conflicted)
conflicts_prefer(
dplyr::filter(),
dplyr::mutate(),
dplyr::summarise(),
dplyr::select(),
DT::dataTableOutput(),
DT::renderDataTable,
)
source("geom_flat_violin.R")
######## Increase maximum upload size to 30 MB #######
options(shiny.maxRequestSize=30*1024^2)
###### Functions ##########
#Function that resamples a vector (with replacement) and calculates the median value
boot_median = function(x) {
median(sample(x, replace = TRUE))
}
#Function that resamples a vector (with replacement) and calculates the mean value
boot_mean = function(x) {
mean(sample(x, replace = TRUE))
}
i=0
#Number of bootstrap samples
nsteps=1000
#Confidence level
Confidence_Percentage = 95
Confidence_level = Confidence_Percentage/100
alpha=1-Confidence_level
lower_percentile=(1-Confidence_level)/2
upper_percentile=1-((1-Confidence_level)/2)
#Several qualitative color palettes that are colorblind friendly
#From Paul Tol: https://personal.sron.nl/~pault/
#Code to generate vectors in R to use these palettes
#Red, Green, Blue, yellow, cyan, purple, grey
Tol_bright <- c('#EE6677', '#228833', '#4477AA', '#CCBB44', '#66CCEE', '#AA3377', '#BBBBBB')
Tol_muted <- c('#88CCEE', '#44AA99', '#117733', '#999933', '#DDCC77', '#CC6677', '#882255', '#AA4499', '#332288', '#DDDDDD')
Tol_light <- c('#BBCC33', '#AAAA00', '#77AADD', '#EE8866', '#EEDD88', '#FFAABB', '#99DDFF', '#44BB99', '#DDDDDD')
#Read a text file (comma separated values)
df_wide_example <- read.csv("Area_in_um-GEFs.csv", na.strings = "")
df_tidy_example <- read.csv("Data_tidy_example.csv", na.strings = "")
# Create a reactive object here that we can share between all the sessions.
vals <- reactiveValues(count=0)
###### UI: User interface #########
ui <- fluidPage(
titlePanel("PlotsOfDifferences - Plots all Of the Data and Differences"),
sidebarLayout(
sidebarPanel(width=3,
conditionalPanel(
condition = "input.tabs=='Plot'",
radioButtons("jitter_type", "Data offset", choices = list("Quasirandom" = "quasirandom",
#Uncomment for sinaplot "Sinaplot" = "sina",
"Random" = "random",
"None; stripes" = "stripes",
"None (for small n)" = "none"), selected = "quasirandom"),
sliderInput("alphaInput", "Visibility of the data", 0, 1, 0.3),
# conditionalPanel(
# condition = "input.adjust_jitter == true",
# sliderInput("jitter_width", "Width:", 0,0.5,0.3),
# checkboxInput(inputId = "random_jitter", label = ("Randomize Jitter"), value = TRUE)
# ),
radioButtons("summaryInput", "Statistics", choices = list("Median" = "median", "Mean" = "mean", "Boxplot (minimal n=10)" = "boxplot", "Violin Plot (minimal n=10)" = "violin"), selected = "median"),
# sliderInput("Input_CI", "Confidence Level", 90, 100, 95),
checkboxInput(inputId = "add_CI", label = HTML("Add 95% CI <br/> (minimal n=10)"), value = FALSE),
sliderInput("alphaInput_summ", "Visibility of the statistics", 0, 1, 1),
radioButtons(inputId = "ordered",
label= "Order of the data/statistics:",
choices = list("As supplied" = "none", "By median value" = "median", "By alphabet/number" = "alphabet"),
selected = "none"),
checkboxInput(inputId = "show_diffs",
label = "Display Effect Size",
value = TRUE),
conditionalPanel(
condition = "input.show_diffs == true",
selectInput("zero", "Set reference (Control):", choices = "")),
h4("Plot Layout"),
checkboxInput(inputId = "rotate_plot",
label = "Rotate plot 90 degrees",
value = FALSE),
checkboxInput(inputId = "no_grid",
label = "Remove gridlines",
value = FALSE),
checkboxInput(inputId = "change_scale",
label = "Change scale",
value = FALSE),
conditionalPanel(condition = "input.change_scale == true",
checkboxInput(inputId = "scale_log_10",
label = "Log scale",
value = FALSE),
textInput("range", "Range for values (min,max)", value = ""),
textInput("diff_range", "Range for differences (min,max)", value = "")),
checkboxInput("color_data", "Use color for the data", value=FALSE),
checkboxInput("color_stats", "Use color for the stats", value=FALSE),
conditionalPanel(
condition = "input.color_data == true || input.color_stats == true",
########## Choose color from list
#selectInput("colour_list", "Colour:", choices = ""),
radioButtons("adjustcolors", "Color palette:", choices = list("Standard" = 1,"Colorblind safe (bright)" = 2,"Colorblind safe (muted)" = 3,"Colorblind safe (light)" = 4, "User defined"=5) , selected = 1),
conditionalPanel(condition = "input.adjustcolors == 5",
textInput("user_color_list", "List of names or hexadecimal codes", value = "turquoise2,#FF2222,lawngreen"),
h5("",
a("Click here for more info on color names",
href = "http://www.endmemo.com/program/R/color.php", target="_blank"))
)),
numericInput("plot_height", "Height (# pixels): ", value = 480),
numericInput("plot_width", "Width (# pixels):", value = 480),
h4("Labels"),
checkboxInput(inputId = "add_title",
label = "Add title",
value = FALSE),
conditionalPanel(
condition = "input.add_title == true",
textInput("title", "Title:", value = "")
),
checkboxInput(inputId = "label_axes",
label = "Change labels",
value = FALSE),
conditionalPanel(
condition = "input.label_axes == true",
textInput("lab_x", "X-axis:", value = ""),
textInput("lab_y", "Y-axis:", value = "")
),
checkboxInput(inputId = "adj_fnt_sz",
label = "Change font size",
value = FALSE),
conditionalPanel(
condition = "input.adj_fnt_sz == true",
numericInput("fnt_sz_ttl", "Size axis titles:", value = 24),
numericInput("fnt_sz_ax", "Size axis labels:", value = 18)),
checkboxInput(inputId = "add_description",
label = "Add figure description",
value = FALSE),
NULL ),
conditionalPanel(
condition = "input.tabs=='Data upload'",
h4("Data upload"),
radioButtons(
"data_input", "",
choices =
list("Example 1 (wide format)" = 1,
"Example 2 (tidy format)" = 2,
"Upload file" = 3,
"Paste data" = 4,
"URL (csv files only)" = 5
)
,
selected = 1),
conditionalPanel(
condition = "input.data_input=='1'"
),
conditionalPanel(
condition = "input.data_input=='3'",
h5("Upload file: "),
fileInput("upload", "", multiple = FALSE),
selectInput("file_type", "Type of file:",
list("text (csv)" = "text",
"Excel" = "Excel"
),
selected = "text"),
conditionalPanel(
condition = "input.file_type=='text'",
radioButtons(
"upload_delim", "Delimiter",
choices =
list("Comma" = ",",
"Tab" = "\t",
"Semicolon" = ";",
"Space" = " "),
selected = ",")),
actionButton("submit_datafile_button",
"Submit datafile")),
conditionalPanel(
condition = "input.data_input=='4'",
h5("Paste data below:"),
tags$textarea(id = "data_paste",
placeholder = "Add data here",
rows = 10,
cols = 20, ""),
actionButton("submit_data_button", "Submit data"),
radioButtons(
"text_delim", "Delimiter",
choices =
list("Tab (from Excel)" = "\t",
"Space" = " ",
"Comma" = ",",
"Semicolon" = ";"),
selected = "\t")),
### csv via URL as input
conditionalPanel(
condition = "input.data_input=='5'",
# textInput("URL", "URL", value = "https://zenodo.org/record/2545922/files/FRET-efficiency_mTq2.csv"),
textInput("URL", "URL", value = ""),
NULL
),
checkboxInput(inputId = "tidyInput",
label = "These data are Tidy",
value = FALSE),
conditionalPanel(
condition = "input.tidyInput==false", selectInput("data_remove", "Select columns to remove", "", multiple = TRUE)),
conditionalPanel(
condition = "input.tidyInput==true",
selectInput("x_var", "Conditions to compare:", choices = ""),
selectInput("y_var", "Variables:", choices = ""),
# selectInput("h_facet", "Separate horizontal:", choices = ""),
# selectInput("v_facet", "Separate vertical:", choices = ""),
NULL
),
# selectInput("use_these_conditions", "Select and order:", "", multiple = TRUE),
# hr(),
conditionalPanel(
condition = "input.tidyInput==false", (downloadButton("downloadData", "Download in tidy format (csv)"))),
hr(),
checkboxInput(inputId = "info_data",
label = "Show information on data formats",
value = FALSE),
conditionalPanel(
condition = "input.info_data==true",
img(src = 'Data_format.png', width = '100%'), h5(""), a("Background info for converting wide data to tidy format", href = "http://thenode.biologists.com/converting-excellent-spreadsheets-tidy-data/education/")
)
),
conditionalPanel(
condition = "input.tabs=='About'",
#Session counter: https://gist.github.com/trestletech/9926129
h4("About"), "There are currently",
verbatimTextOutput("count"),
"session(s) connected to this app.",
hr(),
h4("Find our other dataViz apps at:"),a("https://huygens.science.uva.nl/", href = "https://huygens.science.uva.nl/")
),
conditionalPanel(
condition = "input.tabs=='Summary'",
h4("Data summary"),
checkboxInput(inputId = "calc_p",
label = "Display p-value",
value = FALSE),
p("The p-value is determined by a randomization test, calculation may take some time"),
numericInput("digits_diff", "Digits (Difference):", 3, min = 0, max = 7),
numericInput("digits", "Digits (Summary):", 2, min = 0, max = 7),
checkboxGroupInput("stats_select", label = h5("Statistics for table:"),
choices = list("mean", "sd", "sem","95CI mean", "median", "MAD", "IQR", "Q1", "Q3", "95CI median"),
selected = "sem"),
actionButton('select_all1','select all'),
actionButton('deselect_all1','deselect all')
)
),
mainPanel(
tabsetPanel(id="tabs",
tabPanel("Data upload", h4("Data as provided"), dataTableOutput("data_uploaded")),
tabPanel("Plot", downloadButton("downloadPlotPDF", "Download pdf-file"),
# downloadButton("downloadPlotSVG", "Download svg-file"),
downloadButton("downloadPlotPNG", "Download png-file"),
actionButton("settings_copy", icon = icon("clone"),
label = "Clone current setting"),
actionButton("legend_copy", icon = icon("clone"),
label = "Copy Legend"),
div(`data-spy`="affix", `data-offset-top`="10", withSpinner(plotOutput("coolplot")),
htmlOutput("LegendText", width="200px", inline =FALSE),
NULL)
),
tabPanel("Summary",
conditionalPanel(
condition = "input.summaryInput=='mean'",
h4("Summary of the differences - based on means")),
conditionalPanel(
condition = "input.summaryInput!='mean'",
h4("Summary of the differences - based on medians")),
withSpinner(dataTableOutput('data_diffs')),
h4("Summary of the data"),
withSpinner(dataTableOutput('data_summary'))
),
tabPanel("About", includeHTML("about.html")
)
)
)
)
)
########## SERVER ########
server <- function(input, output, session) {
isolate(vals$count <- vals$count + 1)
###### DATA INPUT ###################
df_upload <- reactive({
if (input$data_input == 1) {
data <- df_wide_example
} else if (input$data_input == 2) {
data <- df_tidy_example
} else if (input$data_input == 3) {
file_in <- input$upload
# Avoid error message while file is not uploaded yet
if (is.null(input$upload)) {
return(data.frame(x = "Select your datafile"))
} else if (input$submit_datafile_button == 0) {
return(data.frame(x = "Press 'submit datafile' button"))
} else {
isolate({
if (input$file_type == "text") {
data <- read_delim(file_in$datapath,
delim = input$upload_delim,
col_names = TRUE)
} else if (input$file_type == "Excel") {
data <- read_excel(file_in$datapath)
}
})
}
} else if (input$data_input == 5) {
#Read data from a URL
#This requires RCurl
if(input$URL == "") {
return(data.frame(x = "Enter a full HTML address, for example: https://zenodo.org/record/2545922/files/FRET-efficiency_mTq2.csv"))
} else if (url.exists(input$URL) == FALSE) {
return(data.frame(x = paste("Not a valid URL: ",input$URL)))
} else {data <- read_csv(input$URL)}
#Read the data from textbox
} else if (input$data_input == 4) {
if (input$data_paste == "") {
data <- data.frame(x = "Copy your data into the textbox,
select the appropriate delimiter, and
press 'Submit data'")
} else {
if (input$submit_data_button == 0) {
return(data.frame(x = "Press 'submit data' button"))
} else {
isolate({
data <- read_delim(input$data_paste,
delim = input$text_delim,
col_names = TRUE)
})
}
}
}
updateSelectInput(session, "data_remove", choices = names(data))
return(data)
})
##### REMOVE SELECTED COLUMNS #########
df_filtered <- reactive({
if (!is.null(input$data_remove)) {
columns = input$data_remove
df <- df_upload() %>% select(-one_of(columns))
} else if (is.null(input$data_remove)) {
df <- df_upload()}
})
##### CONVERT TO TIDY DATA ##########
#Need to tidy the data?!
#Untidy data will be converted to long format with two columns named 'Condition' and 'Value'
#The input for "Condition" will be taken from the header, i.e. first row
#Tidy data will be used as supplied
df_upload_tidy <- reactive({
if(input$tidyInput == FALSE ) {
klaas <- df_filtered() %>% gather(Condition, Value)
}
else if(input$tidyInput == TRUE ) {
klaas <- df_upload()
}
return(klaas)
})
##### Get the Variables (necessary for tidy data with multiple variables) ##############
observe({
var_names <- names(df_upload_tidy())
var_list <- c("none", var_names)
# updateSelectInput(session, "colour_list", choices = var_list)
updateSelectInput(session, "y_var", choices = var_list)
updateSelectInput(session, "x_var", choices = var_list)
})
##### Get the list of Conditions (necessary to select the control condition for comparison) ##############
observe({
########### This is NULL for tidy - needs to be fixed ######
if(input$tidyInput == FALSE ) {
koos <- df_upload_tidy()
conditions_list <- as.factor(koos$Condition)
# observe(print((conditions_list)))
updateSelectInput(session, "zero", choices = conditions_list)
}
})
########### When x_var is selected for tidy data, get the list of conditions
observeEvent(input$x_var != 'none' && input$y_var != 'none', {
if (input$x_var != 'none' && input$y_var != 'none') {
koos <- df_selected()
conditions_list <- as.factor(koos$Condition)
# observe(print((conditions_list)))
updateSelectInput(session, "zero", choices = conditions_list)
}
})
########### GET INPUT VARIABLEs FROM HTML ##############
observe({
############ ?data ################
query <- parseQueryString(session$clientData$url_search)
if (!is.null(query[['data']])) {
presets_data <- query[['data']]
presets_data <- unlist(strsplit(presets_data,";"))
observe(print((presets_data)))
updateRadioButtons(session, "data_input", selected = presets_data[1])
updateCheckboxInput(session, "tidyInput", value = presets_data[2])
#To Implement:
#presets_data[3], x_var
#presets_data[4], y_var
#presets_data[5], h_facet
#presets_data[6], v_facet
}
############ ?vis ################
if (!is.null(query[['vis']])) {
presets_vis <- query[['vis']]
presets_vis <- unlist(strsplit(presets_vis,";"))
observe(print((presets_vis)))
#radio, slider, radio, check, slider
updateRadioButtons(session, "jitter_type", selected = presets_vis[1])
updateSliderInput(session, "alphaInput", value = presets_vis[2])
updateRadioButtons(session, "summaryInput", selected = presets_vis[3])
updateCheckboxInput(session, "add_CI", value = presets_vis[4])
updateSliderInput(session, "alphaInput_summ", value = presets_vis[5])
updateRadioButtons(session, "ordered", selected = presets_vis[6])
# updateTabsetPanel(session, "tabs", selected = "Plot")
}
############ ?layout ################
if (!is.null(query[['layout']])) {
presets_layout <- query[['layout']]
presets_layout <- unlist(strsplit(presets_layout,";"))
observe(print((presets_layout)))
updateCheckboxInput(session, "rotate_plot", value = presets_layout[1])
updateCheckboxInput(session, "no_grid", value = (presets_layout[2]))
updateCheckboxInput(session, "change_scale", value = presets_layout[3])
updateCheckboxInput(session, "scale_log_10", value = presets_layout[4])
updateTextInput(session, "range", value= presets_layout[5])
updateCheckboxInput(session, "color_data", value = presets_layout[6])
updateCheckboxInput(session, "color_stats", value = presets_layout[7])
updateRadioButtons(session, "adjustcolors", selected = presets_layout[8])
updateCheckboxInput(session, "add_description", value = presets_layout[9])
if (length(presets_layout)>10) {
updateNumericInput(session, "plot_height", value= presets_layout[10])
updateNumericInput(session, "plot_width", value= presets_layout[11])
}
# updateTabsetPanel(session, "tabs", selected = "Plot")
}
############ ?color ################
if (!is.null(query[['color']])) {
presets_color <- query[['color']]
presets_color <- unlist(strsplit(presets_color,";"))
updateSelectInput(session, "colour_list", selected = presets_color[1])
updateTextInput(session, "user_color_list", value= presets_color[2])
}
############ ?label ################
if (!is.null(query[['label']])) {
presets_label <- query[['label']]
presets_label <- unlist(strsplit(presets_label,";"))
observe(print((presets_label)))
updateCheckboxInput(session, "add_title", value = presets_label[1])
updateTextInput(session, "title", value= presets_label[2])
updateCheckboxInput(session, "label_axes", value = presets_label[3])
updateTextInput(session, "lab_x", value= presets_label[4])
updateTextInput(session, "lab_y", value= presets_label[5])
updateCheckboxInput(session, "adj_fnt_sz", value = presets_label[6])
updateNumericInput(session, "fnt_sz_ttl", value= presets_label[7])
updateNumericInput(session, "fnt_sz_ax", value= presets_label[8])
updateCheckboxInput(session, "add_description", value = presets_label[9])
}
############ ?url ################
if (!is.null(query[['url']])) {
updateRadioButtons(session, "data_input", selected = 5)
updateTextInput(session, "URL", value= query[['url']])
observe(print((query[['url']])))
updateTabsetPanel(session, "tabs", selected = "Plot")
}
})
########### RENDER URL ##############
output$HTMLpreset <- renderText({
url()
})
######### GENERATE URL with the settings #########
url <- reactive({
base_URL <- paste(sep = "", session$clientData$url_protocol, "//",session$clientData$url_hostname, ":",session$clientData$url_port, session$clientData$url_pathname)
data <- c(input$data_input, input$tidyInput, input$x_var, input$y_var, input$h_facet, input$v_facet)
vis <- c(input$jitter_type, input$alphaInput, input$summaryInput, input$add_CI, input$alphaInput_summ, input$ordered)
layout <- c(input$rotate_plot, input$no_grid, input$change_scale, input$scale_log_10, input$range, input$color_data, input$color_stats,
input$adjustcolors, input$add_description, input$plot_height, input$plot_width)
#Hide the standard list of colors if it is'nt used
if (input$adjustcolors != "5") {
color <- c(input$colour_list, "none")
} else if (input$adjustcolors == "5") {
color <- c(input$colour_list, input$user_color_list)
}
label <- c(input$add_title, input$title, input$label_axes, input$lab_x, input$lab_y, input$adj_fnt_sz, input$fnt_sz_ttl, input$fnt_sz_ax, input$add_description)
#replace FALSE by "" and convert to string with ; as seperator
data <- sub("FALSE", "", data)
data <- paste(data, collapse=";")
data <- paste0("data=", data)
vis <- sub("FALSE", "", vis)
vis <- paste(vis, collapse=";")
vis <- paste0("vis=", vis)
layout <- sub("FALSE", "", layout)
layout <- paste(layout, collapse=";")
layout <- paste0("layout=", layout)
color <- sub("FALSE", "", color)
color <- paste(color, collapse=";")
color <- paste0("color=", color)
label <- sub("FALSE", "", label)
label <- paste(label, collapse=";")
label <- paste0("label=", label)
if (input$data_input == "5") {url <- paste("url=",input$URL,sep="")} else {url <- NULL}
parameters <- paste(data, vis,layout,color,label,url, sep="&")
preset_URL <- paste(base_URL, parameters, sep="?")
observe(print(parameters))
observe(print(preset_URL))
return(preset_URL)
})
############# Pop-up that displays the URL to 'clone' the current settings ################
observeEvent(input$settings_copy , {
showModal(urlModal(url=url(), title = "Use the URL to launch PlotsOfDifferences with the current setting"))
})
observeEvent(input$legend_copy , {
showModal(urlModal(url=Fig_legend(), title = "Legend text"))
})
############# Pop-up appears when a boxplot or violinplot is selected when n<10 ###########
observeEvent(input$summaryInput , {
df_temp <- df_summary_mean()
min_n <- min(df_temp$n)
if (input$summaryInput == "boxplot" && min_n<10) {
showModal(modalDialog(
title = NULL,
"You have selected a boxplot as summary, but one of the conditions has less than 10 datapoints - For n<10 the boxplot is not a suitable summary", easyClose=TRUE, footer = modalButton("Click anywhere to dismiss")
))
} else if (input$summaryInput == "violin" && min_n<10) {
showModal(modalDialog(
title = NULL,
"You have selected a violinplot as summary, but one of the conditions has less than 10 datapoints - For n<10 the violinplot is not a suitable summary", easyClose=TRUE, footer = modalButton("Click anywhere to dismiss")
))
}
})
############# Pop-up appears when the 95%CI is selected when n<10 ###########
observeEvent(input$add_CI , {
df_temp <- df_summary_mean()
min_n <- min(df_temp$n)
if (input$add_CI == TRUE && min_n<10) {
showModal(modalDialog(
title = NULL,
"Confidence Intervals are used to make inferences, but one of the conditions has less than 10 datapoints - It is not recommended to show inferential statistics (CI, sem) for n<10", easyClose=TRUE, footer = modalButton("Click anywhere to dismiss")
))
}
})
############# Pop-up appears when n<10 ###########
observeEvent(input$tabs=="Plot" , {
df_temp <- df_summary_mean()
min_n <- min(df_temp$n)
if (input$show_diffs == TRUE && min_n<10) {
showModal(modalDialog(
title = NULL,
"One of the conditions has less than 10 datapoints - calculating the effect size based on bootsrapping is not recommended", easyClose=TRUE, footer = modalButton("Click anywhere to dismiss")
))
updateCheckboxInput(session, "show_diffs", value = FALSE)
}
})
######## ORDER the Conditions #######
df_sorted <- reactive({
# klaas <- df_upload_tidy()
klaas <- df_selected()
if(input$ordered == "median") {
klaas$Condition <- reorder(klaas$Condition, klaas$Value, median, na.rm = TRUE)
} else if (input$ordered == "none") {
klaas$Condition <- factor(klaas$Condition, levels=unique(klaas$Condition))
} else if (input$ordered == "alphabet") {
klaas$Condition <- factor(klaas$Condition, levels=unique(sort(klaas$Condition)))
}
return(klaas)
})
######## Make a new dataframe with selected variables for display & summary stats #######
df_selected <- reactive({
if(input$tidyInput == TRUE ) {
df_temp <- df_upload_tidy()
if (input$x_var == 'none' || input$y_var == 'none') {
showModal(modalDialog(
title = NULL,
"Error: you need to select a column for the condition and a column for the values", easyClose=TRUE
))
}
x_choice <- input$x_var
y_choice <- input$y_var
koos <- df_temp %>% select(Condition = !!x_choice , Value = !!y_choice) %>% filter(!is.na(Value))
} else if (input$tidyInput == FALSE ) {
koos <- df_upload_tidy() %>% filter(!is.na(Value))
}
return(koos)
})
#### DISPLAY UPLOADED DATA (as provided) ##################
output$data_uploaded <- renderDataTable(
# observe({ print(input$tidyInput) })
df_filtered(),
rownames = FALSE,
options = list(pageLength = 100, autoWidth = FALSE,
lengthMenu = c(10, 100, 1000, 10000)),
editable = FALSE,selection = 'none'
)
########### Caluclate stats for the MEAN ############
df_summary_mean <- reactive({
koos <- df_selected() %>%
group_by(Condition) %>%
summarise(n = n(),
mean = mean(Value),
sd = sd(Value)) %>%
mutate(sem = sd / sqrt(n - 1),
mean_CI_lo = mean + qt((1-Confidence_level)/2, n - 1) * sem,
mean_CI_hi = mean - qt((1-Confidence_level)/2, n - 1) * sem)
return(koos)
})
############ Caluclate stats for the MEDIAN ##########
df_summary_median <- reactive({
klaas <- df_bootstrap_stats()
kees <- df_selected() %>%
group_by(Condition) %>%
summarise(
median= median(Value, na.rm = TRUE),
MAD= mad(Value, na.rm = TRUE, constant=1),
IQR= IQR(Value, na.rm = TRUE),
Q1=quantile(Value, probs=0.25),
Q3=quantile(Value, probs=0.75))
kees$median_CI_lo <- tapply(klaas$resampled_median, klaas$Condition, quantile, probs=lower_percentile)
kees$median_CI_hi <- tapply(klaas$resampled_median, klaas$Condition, quantile, probs=upper_percentile)
return(kees)
})
#### Caluclate boostrap samples for the Median and Mean ####
df_bootstrap_stats <- reactive({
kees <- df_selected()
df_boostraps <- data.frame()
#Perform the resampling nsteps number of times (typically 1,000-10,000x)
for (i in 1:nsteps) {
#Caclulate the median and mean from a boostrapped sample (resampled_median, resampled_mean) and add to the dataframe
df_temp <- data.frame(Condition=levels(factor(kees$Condition)), resampled_median=tapply(kees$Value, kees$Condition, boot_median), resampled_mean=tapply(kees$Value, kees$Condition, boot_mean))
#Add the new median and mean to a datafram that collects all the resampled stats
df_boostraps <- bind_rows(df_boostraps, df_temp)
}
return(df_boostraps)
})
#### Calculate the differences ####
df_diffs <- reactive({
control_condition <- as.character(input$zero)
# observe({ print(control_condition)})
kees <- df_selected()
koos <- df_bootstrap_stats()
#Select the statistic (mean or median) for calculating the difference based on user input
if (input$summaryInput != "mean") {
df_spread <- koos %>% select(Condition, resampled_median) %>% group_by(Condition) %>% mutate(id = 1:n()) %>% spread(Condition, resampled_median)
} else if (input$summaryInput == "mean") {
df_spread <- koos %>% select(Condition, resampled_mean) %>% group_by(Condition) %>% mutate(id = 1:n()) %>% spread(Condition, resampled_mean)
}
#need this to get the base R syntax in the next line to calculate differences to work
df_spread <- as.data.frame(df_spread)
#Subtract the Column with " Control" from the other columns and move these 'differences' into a new dataframe
#there is probably a tidyverse solution using mutate or transmute
# df %>% mutate_at(.funs = funs(diffs = .-Control), .vars = vars(2:ncol(.)))
## Subtracting the control from all Conditions
df_spread_diffs <- df_spread[,2:ncol(df_spread)] - df_spread[,control_condition]
#Convert the dataframe with differences between medians into a long format
df_differences <- gather(df_spread_diffs, Condition, Difference)
return(df_differences)
})
df_summary_diffs <- reactive({
koos <- df_diffs()
df_diff_summary <- koos %>%
group_by(Condition) %>%
summarise(
difference = mean(Difference, na.rm = TRUE),
CI_lo=quantile(Difference, probs=lower_percentile),
CI_hi=quantile(Difference, probs=upper_percentile))
# observe({ print(df_diff_summary)})
return(df_diff_summary)
})
####### Calculate the p-value by randomization #######
df_p <- reactive({
control_condition <- as.character(input$zero)
kees <- df_selected()
df_spread <- kees %>% group_by(Condition) %>% mutate(id = 1:n()) %>% spread(Condition, Value)
#need this to get the base R syntax in the next line to calculate differences to work
df_spread <- as.data.frame(df_spread)
#Extract the list of values that correspond to control condition
# Controls <- (df_spread[,control_condition]) %>% na.omit %>% unlist(use.names = FALSE)
Controls <- df_spread %>% select(!!control_condition) %>% filter(!is.na(.)) %>% unlist(use.names = FALSE)
#Median and mean values as reference/observed values
df_obs_stats <- kees %>% group_by(Condition) %>% summarise(mean=mean(Value, na.rm=TRUE), median=median(Value, na.rm=TRUE))
#generate a df with differences from the observations
df_obs_stats$mean <- df_obs_stats$mean - mean(Controls)
df_obs_stats$median <- df_obs_stats$median - median(Controls)
observe({ print(df_obs_stats)})
#Determine number of observations in Control sample
number_controls <- length(Controls)
observe({ print(number_controls)})
# observe({ print(Controls)})
#Make a new dataframe with control values for each of the conditions
df_controls <- data.frame(Condition=rep(levels(factor(kees$Condition)), each=number_controls), Value=Controls)
#Add the original data, generating (per condition) Control&Sample values in the column "Value".
df_combi <- bind_rows(df_controls, kees) %>% filter(!is.na(Value))
df_new_stats <- data.frame()
#Perform the randomization nsteps number of times (typically 1,000x)
for (i in 1:nsteps) {
#Randomize the dataframe
df_permutated <- df_combi %>% group_by(Condition) %>% sample_frac()
#Determine the (new) control mean and (new) sample mean
df_control <- df_permutated %>% slice(1: number_controls) %>% summarise(new_control_mean=mean(Value), new_control_median=median(Value))
df_sample <- df_permutated %>% slice((number_controls+1):length(Value))%>% summarise(new_sample_mean=mean(Value), new_sample_median=median(Value))
df_diff <- full_join(df_control, df_sample,by="Condition")
df_new_stats <- bind_rows(df_new_stats, df_diff)
}
#Calculate the difference in mean and median (sample-control) for all the calculated new stats
df_all_diffs <- df_new_stats %>% mutate(new_diff_mean=new_sample_mean-new_control_mean,
new_diff_median=new_sample_median-new_control_median)
#Add the observed stats to stats from permutated df
df_all_diffs <- full_join(df_all_diffs, df_obs_stats, by="Condition")
observe({ print(head(df_all_diffs))})
#Determine the occurences where the permutated difference is more extreme than the observed difference
if (input$summaryInput == "mean") {
def_p <- df_all_diffs %>% group_by(Condition) %>% mutate(count = if_else(abs(new_diff_mean) >= abs(mean), 1, 0)) %>% summarise(p_mean=mean(count))
} else if (input$summaryInput != "mean") {
def_p <- df_all_diffs %>% group_by(Condition) %>% mutate(count2 = if_else(abs(new_diff_median) >= abs(median), 1, 0)) %>% summarise(p_median=mean(count2))
}
def_p <- as.data.frame(def_p)
#Replace p-values of zero with <0.001 (0 is theoretically not possible, but an upper bound can estimated, which is 1/nsteps = 1/1000)
def_p[def_p==0]<-"<0.001"
return(def_p)
})
######### DEFINE DOWNLOAD BUTTONS ###########
##### Set width and height of the plot area
width <- reactive ({
width <- input$plot_width