-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.R
1670 lines (1606 loc) · 64.7 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
library(fBasics)
library(shiny)
library(magrittr)
library(nortest)
library(forecast)
library(DT)
options(DT.options = list(pageLength = 20))
# Internal functions of the app
source(file.path("data" , "custom_functions" , "transformFunctions.R"))
# Serie of cool utility functions used from time to time
source(file.path("data" , "custom_functions" , "utilitiesFunctions.R"))
shinyServer(function(input, output,session) {
#Put The Logo
output$myImage <- renderImage({
width <- session$clientData$output_myImage_width
height <- as.character(as.numeric(session$clientData$output_myImage_height)/2)
# For high-res displays, this will be greater than 1
pixelratio <- session$clientData$pixelratio
# filename <- normalizePath(file.path('data', 'Lognormal_distribution.png'))
filename <- normalizePath(file.path('data', 'logo.png'))
list(src = filename, alt="Coolest Logo Ever!", width=width , height=height)
}, deleteFile = FALSE)
#---------------------#
# LOAD DATASET #
#---------------------#
# Create a reactive value for error
dferror <- reactiveValues(myerror=c("Welcome to the Transform Phenotype App!"
,"If you don't have your own dataset or you are not sure about the format"
,"Click on Load Example Dataset ;)"))
# Reactive object with the full dataset
# This object is activated when you upload some data
rawData <- reactive({
# If you click on Load example dataset, it will upload an example
if(!is.null(input$myfile)){
inFile <- input$myfile
} else if(as.logical(input$example)){
inFile <- data.frame(name="exampleDataset.txt"
, datapath=file.path("data" , "exampleDataset.txt")
,stringsAsFactors=FALSE)
} else {
return(NULL)
}
if(nrow(inFile)==1){
out <- read.table(inFile$datapath
, header=TRUE
, sep="\t"
, fill=TRUE
, strip.white=TRUE
, as.is=TRUE
)
} else {
checkCols <- sapply(inFile$datapath , function(x) readLines(x , n=1))
if(any(checkCols!=checkCols[1])){
dferror$myerror <- "You select multiple files with different column names"
return(NULL)
}
fileNames <- if(any(duplicated(inFile$name))){
paste("Cohort" , 1:nrow(inFile) , sep=".")
} else {
inFile$name
}
out <- lapply(1:length(inFile$datapath) , function(x) {
outInternal <- read.table(inFile$datapath[[x]]
, header=TRUE
, sep="\t"
, fill=TRUE
, strip.white=TRUE
, as.is=TRUE
)
if(nrow(outInternal)==0)
return(NULL)
if("InputFileNum" %notin% colnames(outInternal)){
outInternal$InputFileNum <- fileNames[x]
} else {
return(NULL)
}
return(outInternal)
}) %>% do.call("rbind" , .)
if(is.null(out)){
dferror$myerror <- "Either all files are empty or InputFileNum is among the column names"
return(NULL)
}
}
colnames(out) <- tolower(colnames(out))
rawRows <- nrow(out)
out <- unique(out)
if(nrow(out)!=rawRows)
warning("FOUND DUPLICATED ROWS. REMOVED")
#### Check for Sanger Phenotype Database format
# There is currently a typo in the database (phentoype instead of phenotype)
# We accept both forms
if( all(c("genotype" , "phenotype") %in% colnames(out)) | all(c("genotype" , "phentoype") %in% colnames(out)) ){
out$sample_id <- out$genotype
out$phenotype <- NULL
out$phentoype <- NULL
out$genotype <- NULL
}
# If sample_id is among the colnames it is going to be used as sample identifier
# If sample_id doesn't exist, shiny tries with the first column, otherwise dies
if("sample_id" %in% colnames(out)){
out$sample_id <- as.character(out$sample_id)
if( length(unique(out$sample_id))==nrow(out) ){
out <- out[ , c("sample_id" , colnames(out)[colnames(out)!="sample_id"])]
} else {
dferror$myerror <- "sample_id COLUMN HAS DUPLICATED VALUES"
return(NULL)
}
} else if( length(unique(out[ , 1]))==nrow(out) ){
out[ , 1] <- as.character(out[ , 1])
colnames(out)[1] <- "sample_id"
} else {
dferror$myerror <- "FORMAT OF THE FILE NOT SUPPORTED. NEED A SAMPLE_ID COLUMN WITH UNIQUE IDENTIFIERS"
return(NULL)
}
##### Check sex
# At least sex or gender must be present
if( all(c("sex" , "gender") %notin% colnames(out)) ){
dferror$myerror <- "SEX OR GENDER REQUIRED"
return(NULL)
}
if( all(c("sex" , "gender") %in% colnames(out)) ){
if( all(out$sex %eq% out$gender) ){
out$gender <- NULL
warning("FOUND BOTH SEX AND GENDER COLUMNS. KEPT SEX")
} else {
dferror$myerror <- "FOUND BOTH SEX AND GENDER COLUMNS AND THEY ARE DIFFERENT. GET RID OF ONE OF THEM"
return(NULL)
}
} else if("gender" %in% colnames(out)) {
warning("GENDER COLUMN CHANGED TO SEX")
out$sex <- out$gender
out$gender <- NULL
}
# We can accept sex coded as 0/1 or M/F or m/f
# Our standard will be 1/2 (plink style)
out$sex[out$sex==""] <- NA
if( all(na.omit(out$sex) %in% c(0,1)) ){
out$sex <- out$sex + 1
} else if( all( na.omit(tolower(out$sex)) %in% c("m","f")) ){
out$sex <- .mymapvalues(tolower(out$sex) , from=c("m" , "f") , to=c(1,2)) %>%
as.integer
} else if( any( na.omit(out$sex) %notin% c(1,2) ) ){
dferror$myerror <- "UNRECOGNIZED OR MIXED SEX CODIFICATION. REVERT TO 1==MALE , 2==FEMALE"
return(NULL)
}
out$sex <- suppressWarnings( as.numeric(out$sex) )
if("age" %in% colnames(out))
out$age <- suppressWarnings( as.numeric(out$age) )
numTraits <- sapply(out[ , colnames(out) %notin% c("age" , "sex")] , class) %in% c("numeric" , "integer") %>%
which %>%
length
# numStrats <- (length(which(sapply(out , class)=="character")) - 1)
rule1 <- sapply(out , class) %in% c("character" , "integer")
rule2 <- sapply(out , function(x) any(duplicated(x)))
numStrats <- length(which(rule1 & rule2))
dferror$myerror <- c(
"DATA LOADED CORRECTLY:"
,"Numeric Traits (excluding sex and age):" %++% numTraits
,"Sex detected:" %++% c("No" , "Yes")[as.numeric(any(colnames(out)=="sex"))+1]
,"Age detected:" %++% c("No" , "Yes")[as.numeric(any(colnames(out)=="age"))+1]
,"BMI detected:" %++% c("No" , "Yes")[as.numeric(any(colnames(out)=="bmi"))+1]
,"Stratification Variables:" %++% numStrats
)
return(out)
})
# What was wrong with my data?
# Error message about format is stored together with rawData() reactive object
output$dferror <- renderPrint(cat(dferror$myerror , sep="\n"))
# Reactive column of the chosen trait
mytrait <- reactive({
rawData()[[input$trait]]
})
# Show the uploaded table
output$contents <- DT::renderDataTable({
rawData()
} ,rownames=FALSE
,extensions=list(FixedColumns=list(leftColumns = 1))
,options = list(searchHighlight = TRUE
,scrollX = TRUE
,scrollCollapse = FALSE
,pageLength = 10)
,filter = 'bottom'
)
#---------------------------------#
# SELECTOR MODIFIERS #
#---------------------------------#
#Change Trait selector according to the colnames of user table
observe({
updateSelectInput(session , "trait" , "Choose Your Trait:"
, choices= if(is.null(rawData())){
""
}else{
notTraits2 <- c(notTraits
, colnames(rawData())[sapply(rawData() , class)=="character"])
colnames(rawData())[!colnames(rawData()) %in% notTraits2]
}
, selected=if(is.null(rawData())){
""
}else{
notTraits2 <- c(notTraits
, colnames(rawData())[sapply(rawData() , class)=="character"])
colnames(rawData())[!colnames(rawData()) %in% notTraits2][1]
}
)
})
# Modify filter selector, based on min and max value of the trait chosen
observe({
if(input$trait!=""){
filtermin <- min(mytrait() , na.rm=TRUE)
filtermax <- max(mytrait() , na.rm=TRUE)
updateSliderInput(session , "filters" , "Additional filter on raw values:"
,min = filtermin
,max = filtermax
,value = c(filtermin , filtermax)
)
}
})
# Modify Covariates selector adding all variables except the one under analysis
# If age is among the variable, age2 is added too
observe({
if(!is.null(rawData())){
# covariates must be numerical or integer
newchoices <- colnames(rawData())[sapply(rawData() , class)!="character"]
# newchoices <- c(NA , newchoices)
if("age" %in% newchoices)
newchoices <- c(newchoices , "age2") %>% sort
newchoices <- newchoices[ newchoices!=input$trait ]
updateSelectInput(session , "covariates_tested" , "Choose one or more covariate:"
, choices= newchoices
, selected=if("sex" %in% newchoices) "sex" else NA
)
}
})
# Adjust the stratifier
# Stratifiers are all the character columns, except for sample_id column
observe({
if(!is.null(rawData())){
# Rules to be a stratifier:
# being a vector of type character or integer
# contain at least a duplicated value (otherwise the splitting makes no sense)
# sex cannot be a stratifier (it is treated separately)
rule1 <- sapply(rawData() , class) %in% c("character" , "integer")
rule2 <- sapply(rawData() , function(x) any(duplicated(x)))
newstrats <- colnames(rawData())[rule1 & rule2]
stratifiers <- newstrats
stratifiers <- stratifiers[stratifiers %notin% c("sample_id" , "sex")]
updateSelectInput(session , "stratifier" , "Choose one stratification variable:"
, choices=stratifiers
, selected=NULL
)
}
})
#---------------------#
# PROTOCOL GENERATION #
#---------------------#
# Generate protocol file from user choices like filters, transformation type etc.
protocolFile <- reactive({
# filter must be treated separately because of the original format of protocol file
# The slider return a vector with a sort range c(10,20) that becomes <10,>20
if(input$trait!=""){
myfilter <- input$filters %>%
paste(c("<" , ">") , . , sep="") %>%
paste(. , collapse=",")
covariates <- if(is.null(input$covariates_tested)) {
NA
} else {
paste(input$covariates_tested , collapse=",")
}
data.frame(trait=as.factor(input$trait)
,units=input$units
,transformation_method=input$transformation_method
,covariates_tested=covariates
,sd_num=if(input$sd_num=="NA") NA else as.numeric(input$sd_num)
,sd_num_sex=if(input$sd_num_sex=="NA") NA else as.numeric(input$sd_num_sex)
,sd_dir=input$sd_dir
,filters=myfilter
,stringsAsFactors=FALSE
)
} else {
return(NULL)
}
})
#------------------------------------------#
# CREATING TRAITOBJECT USING PROTOCOL #
#------------------------------------------#
# Reduce dataset according to protocol specification
# remove missing sex specification
# remove absolute outliers
# remove tails according to SD specifications
# note: the SD filter is influenced by stratification by sex
# If input$stratifier is not set or is NA, the result is a dataframe
# If input$stratifier is set the result is a list of dataframe
traitObject <- reactive({
if(is.null(rawData())){
return(NULL)
}
# Variable from protocol
altFilter <- protocolFile()$filters
currTrait <- protocolFile()$trait
numSDs <- protocolFile()$sd_num
numSDs_sex <- protocolFile()$sd_num_sex
sdDir <- protocolFile()$sd_dir
covariates <- as.character(protocolFile()$covariates_tested)
covariatesSplit <- unlist(strsplit(covariates , ","))
covList<- list(covariates=covariatesSplit
, age2Flag=if("age2" %in% covariatesSplit) TRUE else NA)
# Remove missing sex
missingSex <- which(is.na(rawData()$sex))
dataset <- rawData()
if(length(missingSex>0)){
dataset <- dataset[-missingSex,]
}
if(is.null(input$stratifier)){
traitObject <- createDF(currTrait,covList,dataset)
# Apply hard filter for oulier
if(!is.na(altFilter)){
outliersFilter <- applyFilters(altFilter,traitObject)
excl <- which(traitObject$ID %in% outliersFilter)
if(length(excl)>0)traitObject <- traitObject[-excl,]
}
females<-which(traitObject$sex==2)
males<-which(traitObject$sex==1)
if(input$sexStratFlag=="Yes"){
if(!is.na(numSDs)){
maleSdOutliers <-findSdOutliers(numSDs,sdDir,traitObject[males,])
femaleSdOutliers <-findSdOutliers(numSDs,sdDir,traitObject[females,])
sdOutliers <- c(maleSdOutliers,femaleSdOutliers)
excl<-which(traitObject$ID %in% sdOutliers)
if(length(excl)>0){
traitObjforRawPlot <- traitObject[-excl,]
} else {
traitObjforRawPlot <- traitObject
}
} else {
traitObjforRawPlot <- traitObject
}
} else {
if(!is.na(numSDs_sex)){
#New from Vincent: SD in non-stratified data can now still be based on sex stratified distribution
maleSdOutliers <-findSdOutliers(numSDs_sex,sdDir,traitObject[males,])
femaleSdOutliers <-findSdOutliers(numSDs_sex,sdDir,traitObject[females,])
sdOutliers <- c(maleSdOutliers,femaleSdOutliers)
excl<-which(traitObject$ID %in% sdOutliers)
if(length(excl)>0){
traitObjforRawPlot <- traitObject[-excl,]
} else {
traitObjforRawPlot <- traitObject
}
#Old method
}else if(!is.na(numSDs)){
sdOutliers <- findSdOutliers(numSDs,sdDir,traitObject)
excl<-which(traitObject$ID %in% sdOutliers)
if(length(excl)>0){
traitObjforRawPlot <- traitObject[-excl,]
} else {
traitObjforRawPlot <- traitObject
}
} else {
traitObjforRawPlot <- traitObject
}
}
return(traitObjforRawPlot)
} else {
datasetsplit <- split(dataset , as.list(dataset[ , input$stratifier , drop=FALSE]))
traitObjectSplit <- lapply(datasetsplit , function(dataset){
traitObject <- createDF(currTrait,covList,dataset)
# Apply hard filter for oulier
if(!is.na(altFilter)){
outliersFilter <- applyFilters(altFilter,traitObject)
excl <- which(traitObject$ID %in% outliersFilter)
if(length(excl)>0)traitObject <- traitObject[-excl,]
}
females<-which(traitObject$sex==2)
males<-which(traitObject$sex==1)
if(input$sexStratFlag=="Yes"){
if(!is.na(numSDs)){
maleSdOutliers <-findSdOutliers(numSDs,sdDir,traitObject[males,])
femaleSdOutliers <-findSdOutliers(numSDs,sdDir,traitObject[females,])
sdOutliers <- c(maleSdOutliers,femaleSdOutliers)
excl<-which(traitObject$ID %in% sdOutliers)
if(length(excl)>0){
traitObjforRawPlot <- traitObject[-excl,]
} else {
traitObjforRawPlot <- traitObject
}
} else {
traitObjforRawPlot <- traitObject
}
} else {
if(!is.na(numSDs_sex)){
#New from Vincent: SD in non-stratified data can now still be based on sex stratified distribution
maleSdOutliers <-findSdOutliers(numSDs_sex,sdDir,traitObject[males,])
femaleSdOutliers <-findSdOutliers(numSDs_sex,sdDir,traitObject[females,])
sdOutliers <- c(maleSdOutliers,femaleSdOutliers)
excl<-which(traitObject$ID %in% sdOutliers)
if(length(excl)>0){
traitObjforRawPlot <- traitObject[-excl,]
} else {
traitObjforRawPlot <- traitObject
}
#Old method
}else if(!is.na(numSDs)){
sdOutliers <- findSdOutliers(numSDs,sdDir,traitObject)
excl<-which(traitObject$ID %in% sdOutliers)
if(length(excl)>0){
traitObjforRawPlot <- traitObject[-excl,]
} else {
traitObjforRawPlot <- traitObject
}
} else {
traitObjforRawPlot <- traitObject
}
}
return(traitObjforRawPlot)
})
names(traitObjectSplit) <- names(datasetsplit)
return(traitObjectSplit)
}
})
#-------------------------------#
# PROTOCOL FILE ADJUSTMENT #
#-------------------------------#
# Display protocol file
output$protocolFile <- renderTable({
if(is.null(protocolFile()))
return(NULL)
protocolFile()
} , row.names=FALSE)
# Follow all attempts of the user
values <- reactiveValues(df_data=NULL)
observeEvent(input$storeattempt , {
temp <- rbind(values$df_data , protocolFile())
temp$transformation_method <- .mymapvalues(temp$transformation_method
, from=names(angela_transformations)
, to=unname(angela_transformations))
values$df_data <- unique(temp)
})
output$cumulativeProtocolFile <- DT::renderDataTable({
if(is.null(protocolFile()))
return(NULL)
else
return(values$df_data)
})
observeEvent(input$deleteattempt , {
if(!is.null(input$cumulativeProtocolFile_rows_selected)){
temp <- values$df_data[ -as.numeric(input$cumulativeProtocolFile_rows_selected) , ]
values$df_data <- temp
}
})
#--------------------------#
# SEX DIFFERENCE PLOT #
#--------------------------#
# This closure is a generator of empty plots with a message
emptyPlotter <-function(message){
renderPlot({
par(mar = c(0,0,0,0))
plot(c(0, 1), c(0, 1), ann = F, bty = 'n', type = 'n', xaxt = 'n', yaxt = 'n')
text(x = 0.5, y = 0.5, message
,cex = 3, col = "black")
})
}
# Plot density curves of trait between males and females
# output$sexplot <- renderPlot({
output$sexplot <- renderUI({
if(is.null(rawData())){
output$sexplotempty <- emptyPlotter("No Data Yet")
return(
plotOutput("sexplotempty" , height="800px")
)
}
# Global parameters, indipendent from traitObject
currTrait <- protocolFile()$trait
traitUnit <- protocolFile()$units
traitLabelFull <- paste(currTrait," (",traitUnit,")",sep="")
# Start checking between sexes
project <- as.character(currTrait)
# Extract covariate field: if it is NA, abort the plot
covariates <- as.character(protocolFile()$covariates_tested)
covariatesSplit <- unlist(strsplit(covariates , ","))
if(!"sex" %in% covariatesSplit){
output$sexplotempty <- emptyPlotter("Select sex in your covariates\nif you want to see this plot")
return(
plotOutput("sexplotempty" , height="800px")
)
}
if(is.null(input$stratifier)){
# Check if sex is among covariates
# Run Wilcoxon test to see if sexes differ and print out density plot
females<-which(traitObject()$sex==2)
males<-which(traitObject()$sex==1)
output$monosexplot <- renderPlot({
sexStratificationPlot(X=traitObject(),m=males,f=females
,label=currTrait,labelFull=traitLabelFull
,project=project)
})
output$sexPlotDownload <- downloadHandler(
filename=function() {
timeTag <- Sys.time() %>%
sub(" GMT$" , "" , .) %>%
gsub(":" , "_" , .) %>%
gsub("-" , "" , .) %>%
sub(" " , "." , .)
paste(protocolFile()$trait , "sex" , timeTag , "pdf" , sep=".")
}
, content=function(file) {
pdf(file , width=16 , height=10)
sexStratificationPlot(X=traitObject(),m=males,f=females
,label=currTrait,labelFull=traitLabelFull
,project=project)
dev.off()
}
)
return(fluidPage(
plotOutput("monosexplot" , height="800px")
,downloadButton("sexPlotDownload" , label = "Download Plot")
)
)
} else {
tabs <- lapply(names(traitObject()) , function(strat){
females<-which(traitObject()[[strat]]$sex==2)
males<-which(traitObject()[[strat]]$sex==1)
output[[paste0(which(strat==names(traitObject())) , "sexstrat_")]] <- renderPlot({
sexStratificationPlot(X=traitObject()[[strat]],m=males,f=females
,label=currTrait,labelFull=traitLabelFull
,project=project)
})
output[[paste0(which(strat==names(traitObject())) , "_sexPlotDownload")]] <- downloadHandler(
filename=function() {
timeTag <- Sys.time() %>%
sub(" GMT$" , "" , .) %>%
gsub(":" , "_" , .) %>%
gsub("-" , "" , .) %>%
sub(" " , "." , .)
paste(protocolFile()$trait , "sex" , input$stratifier , strat , timeTag , "pdf" , sep=".")
}
, content=function(file) {
pdf(file , width=16 , height=10)
sexStratificationPlot(X=traitObject()[[strat]],m=males,f=females
,label=currTrait,labelFull=traitLabelFull
,project=project)
dev.off()
}
)
return(tabPanel(strat
, plotOutput(paste0(which(strat==names(traitObject())) , "sexstrat_") , height="800px")
, downloadButton(paste0(which(strat==names(traitObject())) , "_sexPlotDownload") , label = "Download Plot")
)
)
})
return(do.call(tabsetPanel , tabs))
}
})
# mytransform <- reactiveValues(transformer = NULL)
##### render of the tab Data Plot tab
output$transformer <- renderUI({
if(is.null(rawData())){
output$transformerempty <- emptyPlotter("No Data Yet")
return(
fluidPage(plotOutput("transformerempty" , height="800px"))
)
}
# Protocol Variables
currTrait <- protocolFile()$trait
traitUnit <- protocolFile()$units
traitLabelFull <- paste(currTrait," (",traitUnit,")",sep="")
transformMethod <- protocolFile()$transformation_method
if(is.null(input$stratifier)){
# Initialize transformation side effect output
outputList <- list(paste(transformMethod , "further Normalization Info:"))
if(input$sexStratFlag=="Yes"){
females<-which(traitObject()$sex==2)
males<-which(traitObject()$sex==1)
loop <- c("Males" , "Females")
} else {
loop <- "No Stratification"
}
forPlotandTable <- lapply(loop , function(i){
subs <- if(i=="Males") {
males
} else if(i=="Females"){
females
} else {
1:length(traitObject()$trait)
}
x <- normalizeTraitData(trait=traitObject()$trait[subs] , tm=transformMethod)
if(length(x)>1){
outputList <<- c(outputList , list(i) , list(x[-1]))
} else {
outputList <<- c(outputList , list(i) , list("No other Info"))
}
x <- x$norm_data
return(x)
})
names(forPlotandTable) <- loop
# Store all the output of the transformation, I am sure is going to be useful
# mytransform$transformer <- forPlotandTable
# If radiobutton stratified by sex is on Yes, the plot is run twice for m and f
output$transformerplot <- renderPlot({
return({
if(input$sexStratFlag=="Yes"){
# loop <- c("Males" , "Females")
par(mfrow=c(4,2))
} else {
# loop <- "No Stratification"
par(mfrow=c(2,2))
}
for(i in loop){
normalizationPlot( x = forPlotandTable[[i]] , i = i , traitLabelFull = traitLabelFull)
}
})
})
# Add Download Handler for the plot
output$downloadPlotTransform <- downloadHandler(
filename=function() {
timeTag <- Sys.time() %>%
sub(" GMT$" , "" , .) %>%
gsub(":" , "_" , .) %>%
gsub("-" , "" , .) %>%
sub(" " , "." , .)
paste(protocolFile()$trait , "transform" , timeTag , "pdf" , sep=".")
}
, content=function(file) {
pdf(file , width=16 , height=10)
if(input$sexStratFlag=="Yes"){
# loop <- c("Males" , "Females")
par(mfrow=c(4,2))
} else {
# loop <- "No Stratification"
par(mfrow=c(2,2))
}
for(i in loop){
normalizationPlot( x = forPlotandTable[[i]] , i = i , traitLabelFull = traitLabelFull)
}
dev.off()
})
# Try out basic statistics here (Vincent)
output$basicStatsTable <- renderDataTable(
{
return({
if(input$sexStratFlag=="Yes"){
print(loop)
tmpBS <- basicStats( x = forPlotandTable[['Males']])
malesBS <- tmpBS[c('Skewness','Kurtosis'),]
names(malesBS) <- c('Skewness','Kurtosis')
tmpBS <- basicStats( x = forPlotandTable[['Females']])
femalesBS <- tmpBS[c('Skewness','Kurtosis'),]
names(femalesBS) <- c('Skewness','Kurtosis')
sexStratBS <- data.frame(
Males_Skewness = malesBS['Skewness']
,Males_Kurtosis = malesBS['Kurtosis']
,Females_Skewness = femalesBS['Skewness']
,Females_Kurtosis = femalesBS['Kurtosis']
)
}else{
print(loop)
tmpBS <- basicStats( x = forPlotandTable[["No Stratification"]])
data.frame(Skewness=tmpBS['Skewness',],Kurtosis=tmpBS['Kurtosis',])
}
})
}
,rownames=FALSE
)
# Display all the residual output from transformation (see box cox example)
output$normalizationSideEffect <- renderPrint({
if(is.null(traitObject())){
return(NULL)
}
return(outputList)
})
return({
fluidPage(
plotOutput("transformerplot",height = "800px")
,downloadButton("downloadPlotTransform" , label="Download Plot")
,tags$hr()
,verbatimTextOutput("normalizationSideEffect")
,dataTableOutput("basicStatsTable")
)
})
} else {
# Initialize transformation side effect output
tabs <- lapply(names(traitObject()) , function(strat){
outputList <- list(paste(transformMethod , "further Normalization Info:"))
if(input$sexStratFlag=="Yes"){
females<-which(traitObject()[[strat]]$sex==2)
males<-which(traitObject()[[strat]]$sex==1)
loop <- c("Males" , "Females")
} else {
loop <- "No Stratification"
}
forPlotandTable <- lapply(loop , function(i){
subs <- if(i=="Males") {
males
} else if(i=="Females"){
females
} else {
1:length(traitObject()[[strat]]$trait)
}
x <- normalizeTraitData(trait=traitObject()[[strat]]$trait[subs] , tm=transformMethod)
if(length(x)>1){
outputList <<- c(outputList , list(i) , list(x[-1]))
} else {
outputList <<- c(outputList , list(i) , list("No other Info"))
}
x <- x$norm_data
return(x)
})
names(forPlotandTable) <- loop
# Store all the output of the transformation, I am sure is going to be useful
# mytransform$transformer <- forPlotandTable
# If radiobutton stratified by sex is on Yes, the plot is run twice for m and f
output[[paste0(which(strat==names(traitObject())) , "_transformerplot")]] <- renderPlot({
return({
if(input$sexStratFlag=="Yes"){
# loop <- c("Males" , "Females")
par(mfrow=c(4,2))
} else {
# loop <- "No Stratification"
par(mfrow=c(2,2))
}
for(i in loop){
normalizationPlot( x = forPlotandTable[[i]] , i = i , traitLabelFull = traitLabelFull)
}
})
})
# Add Download Handler for the plot
output[[paste0(which(strat==names(traitObject())) , "_downloadPlotTransform")]] <- downloadHandler(
filename=function() {
timeTag <- Sys.time() %>%
sub(" GMT$" , "" , .) %>%
gsub(":" , "_" , .) %>%
gsub("-" , "" , .) %>%
sub(" " , "." , .)
paste(protocolFile()$trait , "transform" , input$stratifier , strat , timeTag , "pdf" , sep=".")
}
, content=function(file) {
pdf(file , width=16 , height=10)
if(input$sexStratFlag=="Yes"){
# loop <- c("Males" , "Females")
par(mfrow=c(4,2))
} else {
# loop <- "No Stratification"
par(mfrow=c(2,2))
}
for(i in loop){
normalizationPlot( x = forPlotandTable[[i]] , i = i , traitLabelFull = traitLabelFull)
}
dev.off()
})
# Added basic statistics here (Vincent)
output[[paste0(which(strat==names(traitObject())) ,"_basicStatsTable")]] <- renderDataTable(
{
return({
if(input$sexStratFlag=="Yes"){
print(loop)
tmpBS <- basicStats( x = forPlotandTable[['Males']])
malesBS <- tmpBS[c('Skewness','Kurtosis'),]
names(malesBS) <- c('Skewness','Kurtosis')
tmpBS <- basicStats( x = forPlotandTable[['Females']])
femalesBS <- tmpBS[c('Skewness','Kurtosis'),]
names(femalesBS) <- c('Skewness','Kurtosis')
sexStratBS <- data.frame(
Males_Skewness = malesBS['Skewness']
,Males_Kurtosis = malesBS['Kurtosis']
,Females_Skewness = femalesBS['Skewness']
,Females_Kurtosis = femalesBS['Kurtosis']
)
}else{
print(loop)
tmpBS <- basicStats( x = forPlotandTable[["No Stratification"]])
data.frame(Skewness=tmpBS['Skewness',],Kurtosis=tmpBS['Kurtosis',])
}
})
}
,rownames=FALSE
)
# Display all the residual output from transformation (see box cox example)
output[[paste0(which(strat==names(traitObject())) , "_normalizationSideEffect")]] <- renderPrint({
if(is.null(traitObject())){
return(NULL)
}
return(outputList)
})
return({
tabPanel(strat , fluidPage(
plotOutput(paste0(which(strat==names(traitObject())) , "_transformerplot"),height = "800px")
,downloadButton(paste0(which(strat==names(traitObject())) , "_downloadPlotTransform") , label="Download Plot")
,tags$hr()
,verbatimTextOutput(paste0(which(strat==names(traitObject())) , "_normalizationSideEffect"))
,dataTableOutput(paste0(which(strat==names(traitObject())) ,"_basicStatsTable"))
))
})
})
return(do.call(tabsetPanel , tabs))
}
})
#-------------------------------#
# NORMALIZATION TEST TABLE #
#-------------------------------#
# Apply all normalization and calculate normality test
# The output is a table with the pvalue for every transformation
# Yellow color is a NON significant pvalue (that's what we are interested in)
# output$normalTable <- DT::renderDataTable({
output$normalTable <- renderUI({
if(is.null(rawData())){
output$normalTableEmpty <- emptyPlotter("No Data Yet")
return(
plotOutput("normalTableEmpty" , height="800px")
)
}
if(is.null(input$stratifier)){
if(input$sexStratFlag=="Yes"){
Transformation <- names(normalizationFunctionsList)
females<-which(traitObject()$sex==2)
males<-which(traitObject()$sex==1)
loop <- c("Males" , "Females")
normalTable <- lapply(loop , function(sex) {
lapply(Transformation , function(trans) {
subs <- if(sex=="Males") males else if(sex=="Females") females else stop("Error in loop")
x <- normalizeTraitData(trait=traitObject()$trait[subs] , tm=trans)$norm_data
ad <- tryCatch(ad.test(x)$p.value , error=function(e) NA)
sw <- tryCatch(shapiro.test(x)$p.value, error=function(e) NA)
# ks is annoying with warnings in case of ties, so I suppress them
ks <- suppressWarnings({
tryCatch(ks.test(x,rnorm(50))$p.value, error=function(e) NA)
})
return(c(sex , trans , ad , sw , ks))
})
})
normalTable <- lapply(normalTable , function(x) do.call("rbind" , x))
normalTable <- do.call("rbind" , normalTable)
colnames(normalTable) <- c("Sex"
, "Transformation"
, "Anderson-Darling Test"
, "Shapiro-Wilks Test"
, "Kolmogorov-Smirnov Test")
} else if(input$sexStratFlag=="No") {
Transformation <- names(normalizationFunctionsList)
normalTable <- lapply(Transformation , function(trans) {
x <- normalizeTraitData(trait=traitObject()$trait , tm=trans)$norm_data
ad <- tryCatch(ad.test(x)$p.value , error=function(e) NA)
sw <- tryCatch(shapiro.test(x)$p.value, error=function(e) NA)
# ks is annoying with warnings in case of ties, so I suppress them
ks <- suppressWarnings({
tryCatch(ks.test(x,rnorm(50))$p.value, error=function(e) NA)
})
return(c(trans , ad , sw , ks))
})
normalTable <- do.call("rbind" , normalTable)
colnames(normalTable) <- c("Transformation"
, "Anderson-Darling Test"
, "Shapiro-Wilks Test"
, "Kolmogorov-Smirnov Test")
}
output$singleNormalTable <- DT::renderDataTable({
DT::datatable(normalTable) %>%
formatStyle("Anderson-Darling Test"
, backgroundColor = styleInterval(0.05, c('lightgray', 'yellow'))) %>%
formatStyle("Shapiro-Wilks Test"
, backgroundColor = styleInterval(0.05, c('lightgray', 'yellow'))) %>%
formatStyle("Kolmogorov-Smirnov Test"
, backgroundColor = styleInterval(0.05, c('lightgray', 'yellow')))
})
return({
fluidPage(DT::dataTableOutput("singleNormalTable")
,helpText("If you see a yellow box, p-value is over 0.05 and normality test is OK ;=)")
,helpText("Empty cells means that the test could not be evaluated"))
})
} else {
tabs <- lapply(names(traitObject()) , function(strat) {
if(input$sexStratFlag=="Yes"){
Transformation <- names(normalizationFunctionsList)
females<-which(traitObject()[[strat]]$sex==2)
males<-which(traitObject()[[strat]]$sex==1)
loop <- c("Males" , "Females")
normalTable <- lapply(loop , function(sex) {
lapply(Transformation , function(trans) {
subs <- if(sex=="Males") males else if(sex=="Females") females else stop("Error in loop")
x <- normalizeTraitData(trait=traitObject()[[strat]]$trait[subs] , tm=trans)$norm_data
ad <- tryCatch(ad.test(x)$p.value , error=function(e) NA)
sw <- tryCatch(shapiro.test(x)$p.value, error=function(e) NA)
# ks is annoying with warnings in case of ties, so I suppress them
ks <- suppressWarnings({
tryCatch(ks.test(x,rnorm(50))$p.value, error=function(e) NA)
})
return(c(sex , trans , ad , sw , ks))
})
})
normalTable <- lapply(normalTable , function(x) do.call("rbind" , x))
normalTable <- do.call("rbind" , normalTable)
colnames(normalTable) <- c("Sex"
, "Transformation"
, "Anderson-Darling Test"
, "Shapiro-Wilks Test"
, "Kolmogorov-Smirnov Test")
} else if(input$sexStratFlag=="No") {
Transformation <- names(normalizationFunctionsList)
normalTable <- lapply(Transformation , function(trans) {
x <- normalizeTraitData(trait=traitObject()[[strat]]$trait , tm=trans)$norm_data
ad <- tryCatch(ad.test(x)$p.value , error=function(e) NA)
sw <- tryCatch(shapiro.test(x)$p.value, error=function(e) NA)
# ks is annoying with warnings in case of ties, so I suppress them
ks <- suppressWarnings({
tryCatch(ks.test(x,rnorm(50))$p.value, error=function(e) NA)
})
return(c(trans , ad , sw , ks))
})
normalTable <- do.call("rbind" , normalTable)
colnames(normalTable) <- c("Transformation"
, "Anderson-Darling Test"
, "Shapiro-Wilks Test"
, "Kolmogorov-Smirnov Test")
}
output[[paste0(which(strat==names(traitObject())) , "normalTable_")]] <- DT::renderDataTable({
DT::datatable(normalTable) %>%
formatStyle("Anderson-Darling Test"
, backgroundColor = styleInterval(0.05, c('lightgray', 'yellow'))) %>%
formatStyle("Shapiro-Wilks Test"
, backgroundColor = styleInterval(0.05, c('lightgray', 'yellow'))) %>%
formatStyle("Kolmogorov-Smirnov Test"
, backgroundColor = styleInterval(0.05, c('lightgray', 'yellow')))
})
return({
tabPanel(strat
, DT::dataTableOutput(paste0(which(strat==names(traitObject())) , "normalTable_"))
,helpText("If you see a yellow box, p-value is over 0.05 and normality test is OK ;=)")
,helpText("Empty cells means that the test could not be evaluated"))
})
})
do.call(tabsetPanel , tabs)
}
})
# Keep the residual for download
residual <- reactiveValues(df_res=NULL)
output$covariateAnalysis <- renderUI({
if(is.null(rawData())){
output$covariateAnalysisEmpty <- emptyPlotter("No Data Yet")
return(
plotOutput("covariateAnalysisEmpty" , height="800px")
)
}
covariates <- protocolFile()$covariates_tested
covariates <- if(is.null(covariates)) NA else covariates
if(is.na(covariates)){
output$covariateAnalysisEmpty <- emptyPlotter("No covariates selected")
return(
plotOutput("covariateAnalysisEmpty" , height="800px")
)
}
currTrait <- protocolFile()$trait
traitUnit <- protocolFile()$units
traitLabelFull <- paste(currTrait," (",traitUnit,")",sep="")
transformMethod <- protocolFile()$transformation_method
cvr <- unlist(strsplit(covariates , ","))
covList<- list(covariates=cvr
, age2Flag=if("age2" %in% cvr) TRUE else NA)
if(is.null(input$stratifier)){
if(input$sexStratFlag=="Yes"){
cvr <- unlist(strsplit(covariates , ",")) %>% .[.!="sex"]
if(length(cvr)==0){
mymex <- "If you stratify by sex, you can't have sex...\n\n... as the only covariate :)"
output$covariateAnalysisEmpty <- emptyPlotter(mymex)
return(