-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.R
5150 lines (4803 loc) · 207 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
# Shiny Caret is an interactive interface for using various machine learning methods from the caret package
# (c) Nick Ward (University of Canterbury) 2018-2020 ----
# Server Code ------------------------------------------------------
shinyServer(function(input, output, session) {
# input ServerFile ------------------------------------------------------
shinyFiles::shinyFileChoose(input, 'ServerFile', session = session, roots = roots, defaultRoot = "wd")
# reactive values ------------------------------------------------------
react <- reactiveValues(
ModelSet = list(),
Recipe = NULL,
RecipeChanged = 0,
Log = c(),
Warn = c(),
AllowEnsemble = FALSE,
Prob2Class = FALSE,
MethodSet = c(),
Help = TRUE,
HighCardinality = c(),
ROC = NULL,
File = NULL
)
# on session ended ------------------------------------------------------
onSessionEnded(fun = function() {
print("Session ended")
# rm(list = ls(all.names = TRUE))
# gc()
})
# reactive function getProjects ----------------------------------------------
getProjects <- reactive({
files <- file.info(list.files(PROJECT_FOLDER, full.names = TRUE), extra_cols = FALSE)
key <- !files$isdir & str_ends(rownames(files), ".RDA")
proj <- rownames(files)[key]
proj <- sub(pattern = paste0("^", PROJECT_FOLDER, .Platform$file.sep), replacement = "", x = proj)
sub(pattern = "\\.RDA$", replacement = "", x = proj)
})
# observe event Save ------------------------------------------------------
observeEvent(input$Save, {
req(input$Project != "")
print("Saving state")
if (!dir.exists(PROJECT_FOLDER)) {
dir.create(PROJECT_FOLDER)
}
FileName <- paste0(PROJECT_FOLDER, .Platform$file.sep, input$Project, ".RDA")
INPUT <- shiny::reactiveValuesToList(input)
REACT <- shiny::reactiveValuesToList(react)
save(list = c("INPUT", "REACT"), file = FileName)
})
# Reactive Poll loadProject ----------------------------------------------------
loadProject <- reactive({
input$Save
f <- paste0(PROJECT_FOLDER, .Platform$file.sep, isolate(input$Project), ".RDA")
cat("Project file", f, "read\n")
load(f, envir = .GlobalEnv)
}
)
# observe event LoadProject ------------------------------------------------------
observe({
input$LoadProjectReq
req(isolate(input$Project != ""))
shinyjs::disable(id = "LoadProjectReq")
loadProject()
changed <- 0
for (id in names(INPUT)) {
VAR <- isolate(input[[id]])
if (!equals(VAR, INPUT[[id]])) {
# Avoid processing buttons of all kinds (Action & bsButton)
if (id %in% c("help", "Save", "Next", "LoadProjectReq", "Evaluate", "Restart",
"RefreshModels", "Suggest", "ChooseAll", "Install", "Reset", "Train",
"Pause", "UndoModel", "AddModel", "GradTrain")) {
# Avoid processing file inputs of any kind
} else if (id %in% c("LocalFile", "ServerFile")) {
# do nothing
# Avoid processing the non-tab menus
} else if (id %in% c("Submenu", "Submenu_state", "sidebarItemExpanded")) {
# Special processing for Plotly events
} else if (grepl(pattern = "^plotly_.*", x = id)) {
# do nothing
# Special processing for DT::Table events
} else if (grepl(pattern = ".*_(rows_|cells_|search|row_last_).*", x = id)) {
table <- gsub(pattern = "_(rows_|cells_|search).*", replacement = "", x = id)
if (stringr::str_ends(string = id, pattern = "_rows_selected")) {
DTproxy <- DT::dataTableProxy(table)
print(paste("Updating", id, "from", VAR, "to", INPUT[[id]]))
DT::selectRows(proxy = DTproxy, selected = INPUT[[id]], ignore.selectable = TRUE)
#changed <- changed + 1 # As this does not reflect in Table_rows_selected it must be trusted to have occurred
} else if (stringr::str_ends(string = id, pattern = "_search")) {
DTproxy <- DT::dataTableProxy(table)
print(paste("Updating", id, "from", VAR, "to", INPUT[[id]]))
DT::updateSearch(proxy = DTproxy, keywords = list(global = INPUT[[id]], columns = NULL))
#changed <- changed + 1 # As this does not reflect in Table_search it must be trusted to have occurred
}
} else if (is.numeric(VAR) | is.numeric(INPUT[[id]])) {
print(paste("Updating", id, "from", VAR, "to", INPUT[[id]]))
updateSliderInput(session = session, inputId = id, value = INPUT[[id]])
changed <- changed + 1
} else if (is.logical(VAR) | is.logical(INPUT[[id]])) {
print(paste("Updating", id, "from", VAR, "to", INPUT[[id]]))
updateCheckboxInput(session = session, inputId = id, value = INPUT[[id]])
changed <- changed + 1
} else if (id %in% c("Sep", "Quote", "Decimal", "ProbType", "PredictorsTag", "ResultsFor", "SelectedModel")) {
print(paste("Updating", id, "from", VAR, "to", INPUT[[id]]))
updateRadioButtons(session = session, inputId = id, selected = INPUT[[id]])
changed <- changed + 1
} else if (id %in% c("URL", "DateFormat")) {
print(paste("Updating", id, "from", VAR, "to", INPUT[[id]]))
updateTextInput(session = session, inputId = id, value = INPUT[[id]])
changed <- changed + 1
} else if (id %in% c("DataSource", "Navbar", "TrainTab")) {
print(paste("Updating", id, "from", VAR, "to", INPUT[[id]]))
updateTabItems(session = session, inputId = id, selected = INPUT[[id]])
changed <- changed + 1
} else if (id %in% c()) {
print(paste("Updating", id, "from", VAR, "to", INPUT[[id]]))
updateTabItems(session = session, inputId = id, selected = INPUT[[id]])
changed <- changed + 1
} else if (is.character(VAR) | is.character(INPUT[[id]])) {
print(paste("Updating", id, "from", VAR, "to", INPUT[[id]]))
updateSelectizeInput(session = session, inputId = id, selected = INPUT[[id]]) #Assume no selectInput()
changed <- changed + 1
}
}
}
for (id in names(REACT)) {
VAR <- isolate(react[[id]])
if (!equals(VAR, REACT[[id]])) {
print(paste0("Updating react$", id))
react[[id]] <- REACT[[id]]
}
}
# ResultsFor update is masked behind a button
if (length(react$ModelSet) > 0) {
updateRadioButtons(session = session, inputId = "ResultsFor", choices = names(react$ModelSet), selected = INPUT$ResultsFor)
}
if (changed > 0) {
print(paste("Changed =", changed))
invalidateLater(millis = 2000, session = session)
} else {
showNotification(ui = "Project-load completed", duration = 5, type = "message")
shinyjs::enable(id = "LoadProjectReq")
}
}, priority = -10)
# observe event Package ------------------------------------------------------
observeEvent(input$Package, {
results <- data(package = input$Package)$results
if (nrow(results) == 0 || ncol(results) != 4) {
updateSelectizeInput(session = session, inputId = "DataSet", choices = "", selected = "")
} else {
choices <- try({
results <- data.frame(results, stringsAsFactors = FALSE)
results$key <- paste0(results$Item," - ", results$Title)
results <- results[ !duplicated(results$key), ]
choices <- results$Item
names(choices) <- results$key
choices
}, silent = TRUE)
if (length(choices) == 0) {
updateSelectizeInput(session = session, inputId = "DataSet", choices = "")
} else {
updateSelectizeInput(session = session, inputId = "DataSet", choices = as.list(choices))
}
}
})
# reactive function LoadFileType ------------------------------------------------------
LoadFileType <- reactive({
d <- tryCatch({
# when reading semicolon separated files, having a comma separator causes `read.csv` to error - hence the trycatch
if (grepl("\\.csv$", react$File, ignore.case = TRUE)) {
dd <- read.csv(react$File, header = input$Header, sep = input$Sep, quote = input$Quote, na.strings = input$MissingStrings,
dec = input$Decimal, check.names = TRUE, strip.white = TRUE, stringsAsFactors = FALSE)
dd
} else if (grepl("\\.xls.{0,1}$", react$File, ignore.case = TRUE)) {
dd <- as.data.frame(readxl::read_excel(react$File, sheet = 1, na = input$MissingStrings, col_names = input$Header))
dd
} else if (grepl("\\.rdata$", react$File, ignore.case = TRUE)) {
# when reading semicolon separated files, having a comma separator causes `read.csv` to error - hence the trycatch
loaded <- new.env()
what <- load(react$File, envir = loaded)
req(len(what) > 0)
if (length(what) > 1) {
#create alert to resolve VarName
choices <- what[base::apply(X = what, FUN = is.data.frame)]
showElement(id = "VarName")
# updateSelectizeInput(session = session, inputId = "VarName", choices = choices)
get(input$VarName, envir = loaded)
} else {
hideElement(id = "VarName")
get(what, envir = loaded)
}
}
},
warn = function(e) {
shinyalert(title = paste0("File \"",react$File,"\" did not load"), text = e$message, type = "warning")
NULL},
error = function(e) {
shinyalert(title = paste0("File \"",react$File,"\" did not load"), text = e$message, type = "error")
NULL
})
names(d) <- make.names(names(d),unique = TRUE)
d
})
# reactive function loadR ------------------------------------------------------
loadR <- reactive({
d <- tryCatch({
if (input$Package == "All") {
data(list = input$DataSet)
get(input$DataSet)
} else {
data(list = input$DataSet, package = input$Package)
get(input$DataSet, asNamespace(input$Package))
}
},
warn = function(e) {
shinyalert(title = paste0("Dataset \"",input$DataSet,"\" did not load"), text = e$message, type = "warning")
NULL},
error = function(e) {
shinyalert(title = paste0("Dataset \"",input$DataSet,"\" did not load"), text = e$message, type = "error")
NULL
})
})
# reactive Continuous ####------------------------------------------------------------
Continuous <- reactive({
input$Continuous
})
getContinuousDebounced <- debounce(Continuous, millis = 1000)
observeEvent(input$ServerFile, {
file <- parseFilePaths(roots, input$ServerFile)[1,"datapath", drop = TRUE]
req(file)
updateTextInput(session = session, inputId = "ServerFileName", value = as.character(file))
})
observeEvent(input$LocalFile, {
file <- input$LocalFile[1,"datapath", drop = TRUE]
req(file)
updateTextInput(session = session, inputId = "LocalFileName", value = as.character(file))
})
observe({
req(input$Project == "")
updateSelectizeInput(session = session, inputId = "Project", choices = getProjects(), selected = input$Project)
})
# reactive function getRawData ------------------------------------------------------
getRawData <- reactive({
req(input$DataSource)
if (input$DataSource == "Server Data File") {
req(input$ServerFileName != "")
react$File <- input$ServerFileName
d <- LoadFileType()
name <- gsub(pattern = ".*(/|\\\\)", replacement = "", x = input$ServerFileName)
updateSelectizeInput(session = session, inputId = "Project", choices = c(name, isolate(getProjects())), selected = name)
} else if (input$DataSource == "Local Data File") {
req(input$LocalFileName != "")
react$File <- input$LocalFileName
d <- LoadFileType()
name <- gsub(pattern = ".*(/|\\\\)", replacement = "", x = input$LocalFileName)
updateSelectizeInput(session = session, inputId = "Project", choices = c(name, isolate(getProjects())), selected = name)
} else if (input$DataSource == "Remote Data Resource") {
req(input$URL)
URL <- input$URL
react$File <- URL
updateSelectizeInput(session = session, inputId = "Project", choices = c(URL, isolate(getProjects())), selected = URL)
d <- LoadFileType()
} else if (input$DataSource == "Package Dataset") {
req(input$Package != "", input$DataSet != "")
name <- paste(sep = "::", input$Package, input$DataSet)
updateSelectizeInput(session = session, inputId = "Project", choices = c(name, isolate(getProjects())), selected = name)
d <- loadR()
}
req(d, nrow(d) > 0, ncol(d) > 0)
showNotification(id = "checking", ui = "Checking column types", duration = NULL)
# converts whole-number columns to "integer"
numCols <- which(allClass(d) == "numeric")
for (col in numCols) {
if (all(is.wholenumber(d[,col]))) {
showNotification(ui = paste("Changing numeric column", colnames(d)[col], "to integer"), duration = 3)
d[,col] <- as.integer(d[,col])
}
}
# converts 100% compatible character columns back to date variables
charCols <- which(allClass(d) %in% c("character","factor"))
for (col in charCols) {
dates <- as.Date(d[,col], format = input$DateFormat)
if (all(is.na(dates) == is.na(d[,col]))) {
showNotification(ui = paste("Changing character column", colnames(d)[col], "to date"), duration = 3)
d[,col] <- dates
}
}
# converts <= 15 unique levels to factor
charCols <- which(allClass(d) == "character")
max <- nrow(d)
for (col in charCols) {
if (length(unique(d[,col])) <= getContinuousDebounced()[1]) {
showNotification(ui = paste("Changing text column", colnames(d)[col], "to factor"), duration = 3)
d[,col] <- as.factor(d[,col])
}
}
updateTextInput(session = session, inputId = "Project", value = input$CSVFile$name)
d
removeNotification(id = "checking")
choices <- formattedColNames(d)
CHOICES <- toupper(choices)
#set a default value for input$Target and appropriate choices
best <- c( choices[CHOICES == "TARGET"],
choices[CHOICES == "Y"],
choices[CHOICES == "CLASS"],
choices[CHOICES == "LABEL"],
choices[CHOICES == "CHURN"],
rev(choices)
)
guess <- best[1]
updateSelectizeInput(session = session, inputId = "Target", choices = as.list(choices), selected = as.list(guess))
updateSelectizeInput(session = session, inputId = "Weights", selected = "")
updateSelectizeInput(session = session, inputId = "PreSplit", selected = "")
updateSelectizeInput(session = session, inputId = "ID", selected = list())
updateSelectizeInput(session = session, inputId = "HideCol", selected = list())
updateSelectizeInput(session = session, inputId = "Group", selected = NULL)
updateCheckboxInput(session = session, inputId = "AddWeights", value = FALSE)
updateSelectizeInput(session = session, inputId = "BalanceFactors", selected = NULL)
d
})
# render ObservationCount ------------------------------------------------------
output$ObservationCount <- renderInfoBox({
d <- getRawData()
infoBox(title = "Observations", value = nrow(d), icon = icon("align-justify"), color = DATAColour, fill = TRUE )
})
# render VariableCount ------------------------------------------------------
output$VariableCount <- renderInfoBox({
d <- getRawData()
infoBox(title = "Variables", value = ncol(d), icon = icon("columns"), color = DATAColour, fill = TRUE)
})
# reactive GetData ------------------------------------------------------
getData <- reactive({
d <- getRawData()
req(d)
req(nrow(d) > 0, ncol(d) > 0, length(colnames(d)) > 0)
# ensure target is factor for Classification
if (isRoleValid(input$Target, d) && is.binary(d[, input$Target, drop = TRUE])) {
tar <- d[, input$Target]
d[, input$Target] <- as.factor(tar)
showNotification(ui = "Converting binary outcome variable to nominal", type = "warning")
}
#clean up invalid factor level names
for (col in 1:ncol(d)) {
var <- d[,col, drop = TRUE]
if (is(var, "factor")) {
newNames <- make.names(levels(var))
if (any(newNames != levels(var))) {
levels(d[,col]) <- newNames
#print(levels(d[,col]))
}
}
}
if (input$AddWeights && length(input$BalanceFactors) > 0) {
d <- observationWeights(factors = input$BalanceFactors, data = d)
}
if (input$AddIds) {
if (!any(is.na(as.numeric(rownames(d))))) {
d$RowName <- as.numeric(rownames(d))
} else {
d$RowName <- rownames(d)
}
}
d
})
# render Data ------------------------------------------------------
output$Data <- DT::renderDataTable({
d <- getData()
dt <- DT::datatable(data = d, rownames = TRUE, selection = "none",
extensions = c('Scroller','FixedHeader'),
options = list(
scrollX = TRUE,
deferRender = TRUE,
scrollY = 540,
scroller = TRUE
))
numericCols <- colnames(d)[unlist(lapply(d, is.numeric))]
integerCols <- colnames(d)[unlist(lapply(d, is.wholenumber))]
numericCols <- setdiff(numericCols, integerCols)
if (length(numericCols) > 0) {
dt <- formatRound(table = dt, columns = numericCols, digits = 2)
}
if (length(integerCols) > 0) {
dt <- formatRound(table = dt, columns = integerCols, digits = 0)
}
dt
})
# reactive function getSomeRawData ------------------------------------------------------
getSomeRawData <- reactive({
# grab a representative subsample of the data
d <- getRawData()
req(is(d,"data.frame"))
mrow <- getMaxRowsDebounced()
if (nrow(d) <= mrow) {
return(d)
} else {
rows <- sample(nrow(d), mrow)
#preserve order
rows <- sort(rows, decreasing = FALSE)
return(d[rows,])
}
})
# reactive getMaxRows ------------------------------------------------------
MaxRows <- reactive({
input$MaxRows
})
getMaxRowsDebounced <- debounce(MaxRows, millis = 1000)
# reactive getSomeData ------------------------------------------------------
getSomeData <- reactive({
# grab a representative subsample of the data
d <- getData()
req(is(d,"data.frame"))
if (input$ID != "" & input$ID %in% colnames(d)) {
rownames(d) <- d[, input$ID]
}
mrow <- getMaxRowsDebounced()
if (nrow(d) <= mrow) {
return(d)
} else {
rows <- sample(nrow(d), mrow)
#preserve order
rows <- sort(rows, decreasing = FALSE)
return(d[rows,])
}
})
# reactive getSomePredictorData ------------------------------------------------------
# predictors plus outcome - actually
getSomePredictorData <- reactive({
d <- getSomeData()
leaveOut <- getNonPredictors()
d[, !colnames(d) %in% leaveOut]
})
# reactive getPredictorData ------------------------------------------------------
# predictors plus outcome - actually
getPredictorData <- reactive({
d <- getData()
leaveOut <- getNonPredictors()
d[, !colnames(d) %in% leaveOut]
})
# reactive getRawDataSummary ------------------------------------------------------
getRawDataSummary <- reactive({
d <- getSomeRawData()
DataSummary(d)
})
Multiplier <- reactive({
input$Multiplier
})
getMultiplier <- debounce(Multiplier, millis = 1000)
# reactive getDataSummary ------------------------------------------------------
getDataSummary <- reactive({
d <- getSomeData()
DataSummary(d, getMultiplier(), input$UseYJ)
})
# observe ------------------------------------------------------
observe({
d <- getRawData()
req(d)
req(ncol(d) > 0)
ds <- getRawDataSummary()
choices <- colnames(d)
names(choices) <- paste0(choices, " [", ds$type, "]")
#set appropriate choices
updateSelectizeInput(session = session, inputId = "HideCol", choices = as.list(choices))
})
# reactive getDataSummary ------------------------------------------------------
getIDChoices <- reactive({
ds <- getDataSummary()
choicesID <- rownames(ds)
names(choicesID) <- paste0(choicesID, " [",ds$type,"]")
index <- ds$uniqueRatio == 1 & (ds$wholeNumb | ds$text | ds$date)
if (any(index)) {
choicesID <- choicesID[index]
} else {
choicesID <- c()
}
as.list(choicesID)
})
# observe event AddIds ------------------------------------------------------
# observeEvent(
# input$AddIds,
# {
# #set a default value for input$ID and appropriate choices
# if (input$AddIds) {
# updateSelectizeInput(session = session, inputId = "ID", choices = c("RowName"), selected = "RowName")
# shinyjs::disable(id = "ID")
# } else {
# existID <- input$ID
# choicesID <- getIDChoices()
# if (!all(existID %in% choicesID)) {
# existID <- NULL
# }
# updateSelectizeInput(session = session, inputId = "ID", choices = choicesID, selected = existID)
# shinyjs::enable(id = "ID")
# }
# }
# )
# observe ------------------------------------------------------
observe({
ds <- getDataSummary()
req(ds)
choices <- as.list(rownames(ds))
names(choices) <- paste0(choices, " [",ds$type,"]")
imbalanced <- choices[ds$imbalanceRatio > 1.1]
imbalanced[is.na(imbalanced)] <- FALSE
if (input$AddWeights && length(input$BalanceFactors) > 0) {
updateSelectizeInput(session = session, inputId = "Weights", choices = list("Weighting"), selected = "Weighting")
shinyjs::disable(id = "Weights")
} else {
wChoices <- choices[ds$numeric & !ds$binary]
wChoices[["none"]] <- ""
updateSelectizeInput(session = session, inputId = "Weights", choices = wChoices, selected = isolate(input$Weights))
shinyjs::enable(id = "Weights")
}
if (input$PreSplit != "") {
updateSelectizeInput(session = session, inputId = "Groups", choices = list("none" = ""), selected = NULL)
shinyjs::disable(id = "Groups")
} else {
gChoices <- choices[(ds$factor | ds$wholeNum) & ds$uniqueness > 5]
gChoices[["none"]] <- ""
updateSelectizeInput(session = session, inputId = "Groups", choices = gChoices, selected = isolate(input$Groups))
shinyjs::enable(id = "Groups")
}
lowCard <- setdiff(choices[ds$uniqueness <= input$Continuous[1] & ds$uniqueness > 1], c(input$PreSplit, input$Groups))
updateSelectizeInput(session = session, inputId = "BalanceFactors", choices = lowCard, selected = isolate(input$BalanceFactors))
shinyjs::toggle(id = "BalanceFactors", condition = input$AddWeights)
pChoices <- choices[ds$binary | (ds$factor & ds$uniqueness == 2)]
pChoices[["none"]] <- ""
updateSelectizeInput(session = session, inputId = "PreSplit", choices = pChoices, selected = isolate(input$PreSplit))
ids <- getIDChoices()
if (length(ids) == 0) {
# updateCheckboxInput(session = session, inputId = "AddIds", value = TRUE) #triggers before length(ids) has settled down
} else if (length(ids) == 1) {
updateSelectizeInput(session = session, inputId = "ID", choices = ids, selected = ids[1])
} else {
updateSelectizeInput(session = session, inputId = "ID", choices = ids, selected = isolate(input$ID), )
}
})
# observe event Target ------------------------------------------------------
observeEvent(input$Target, {
ds <- getDataSummary()
ds <- ds[rownames(ds) == input$Target, ]
if (nrow(ds) == 0) {
ptype <- NA
} else if (ds$binary | ds$factor | (ds$wholeNumb & ds$uniqueness < getContinuousDebounced()[1]) ) {
ptype <- "Classification"
} else if (ds$numeric & ds$uniqueRatio > 0.5) { #arbitrary 50% unique
ptype <- "Regression"
} else {
ptype <- NA
}
if (is.na(ptype)) {
updateRadioButtons(session = session, inputId = "ProbType", selected = "Any")
} else {
updateRadioButtons(session = session, inputId = "ProbType", selected = ptype)
}
})
# render plot ClassPieChart ------------------------------------------------------
output$ClassPieChart <- renderPlot({
d <- getSomeData()
req(isRoleValid(input$Target, d))
target <- d[,input$Target, drop = TRUE]
req(is.factor(target) || is.binary(target))
if(isRoleValid(input$Weights, d)) {
df <- data.frame(var = target, wt = d[,input$Weights])
t <- df %>% dplyr::count(var, wt = wt)
} else {
df <- data.frame(var = target)
t <- df %>% dplyr::count(var)
}
colnames(t)[1] <- "Level"
ggplot(data = t, mapping = aes(x = 0, y = n, fill = Level)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y") +
labs(title = NULL, x = NULL, y = NULL) +
theme(axis.text.x = element_blank(),
legend.position = "none",
axis.ticks = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.text = element_blank(),
axis.ticks.length = unit(0, "mm"),
plot.margin = unit(c(0,0,0,0), "mm"),
plot.background = element_blank(),
legend.spacing = unit(c(0,0,0,0), "mm"),
axis.title = element_blank()
)
}, bg = "transparent")
# render plot GroupPieChart ------------------------------------------------------
output$GroupPieChart <- renderPlot({
req(input$Groups != "")
d <- getSomeData()
column <- d[,input$Groups, drop = TRUE]
Level <- as.factor(column)
t <- table(Level, useNA = "no")
df <- as.data.frame(t)
ggplot(data = df, mapping = aes(x = 0, y = Freq, fill = Level)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y") +
labs(title = NULL, x = NULL, y = NULL) +
theme(axis.text.x = element_blank(),
legend.position = "none",
axis.ticks = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.text = element_blank(),
axis.ticks.length = unit(0, "mm"),
plot.margin = unit(c(0,0,0,0), "mm"),
plot.background = element_blank(),
legend.spacing = unit(c(0,0,0,0), "mm"),
axis.title = element_blank()
)
}, bg = "transparent")
# render plot SplitPieChart ------------------------------------------------------
output$SplitPieChart <- renderPlot({
d <- getSomeData()
req(isRoleValid(input$PreSplit, d))
df <- data.frame(var = d[,input$PreSplit])
t <- df %>% dplyr::count(var)
colnames(t)[1] <- "Level"
ggplot(data = t, mapping = aes(x = 0, y = n, fill = Level)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y") +
labs(title = NULL, x = NULL, y = NULL) +
theme(axis.text.x = element_blank(),
legend.position = "none",
axis.ticks = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.text = element_blank(),
axis.ticks.length = unit(0, "mm"),
plot.margin = unit(c(0,0,0,0), "mm"),
plot.background = element_blank(),
legend.spacing = unit(c(0,0,0,0), "mm"),
axis.title = element_blank()
)
}, bg = "transparent")
# reactive getNonPredictors ------------------------------------------------------
getNonPredictors <- reactive({
ignore <- c(input$ID, input$Weights, input$PreSplit, input$HideCol, input$Groups)
ignore[ignore != ""]
})
# observe ------------------------------------------------------
observe({
req(input$Navbar == "DataColumns")
d <- getSomeData()
req(d)
req(isRoleValid(input$Target, d))
col <- d[,input$Target, drop = TRUE]
type <- class(col)
if (isRoleValid(input$Weights, d)) {
Xweighted <- "weighted "
} else {
Xweighted <- ""
}
uniqCnt <- length(unique(na.omit(col)))
if (uniqCnt == 1) {
text <- paste("Error: The outcome has constant data.\nIt is not a legitimate outcome variable.")
} else if ("Date" %in% type) {
text <- paste("Warning: This outcome is a date/time variablea.\nIt is not a legitimate outcome variable.")
} else if (is.numeric(col)) {
isInt <- is.wholenumber(col)
if (isInt & uniqCnt < input$Continuous[1]) {
text <- paste("Warning: There are", uniqCnt, "unique integer outcome values.\nTo make a multi-class classification problem you should explicitly change the outcome to a factor")
} else if (!isInt & uniqCnt < input$Continuous[2]) {
text <- paste("Warning: The outcome has only", uniqCnt, "unique numeric values.\nIt is a dubious outcome variable for regression")
} else {
text <- paste0("This is a ", Xweighted ," regression problem.")
}
} else if ("character" %in% type) {
text <- paste("Warning: The outcome is textual data and is not a legitimate outcome variable")
} else if ("factor" %in% type) {
if (uniqCnt == 2 && nrow(d) > 2) {
text <- paste0("This is a ", Xweighted ,"binary classification problem.")
} else if (uniqCnt > input$Continuous[2]) {
text <- paste("Error: The outcome has", uniqCnt, "factor levels.\nIt is not a legitimate outcome variable for classification.")
} else if (uniqCnt > input$Continuous[1]) {
text <- paste("Warning: The outcome has", uniqCnt, "factor levels.\nIt is a dubious outcome variable for classification.")
} else {
text <- paste0("This is a ", Xweighted ,"multinomial classification problem with ",uniqCnt," levels.")
}
} else {
text <- paste0("Error: The outcome type is '", type,"'.\nIt is not a legitimate outcome variable.")
}
targetMessage <- text
output$TargetCheck <- renderInfoBox({
infoBox(title = "Outcome", value = targetMessage, icon = icon("bullseye"), color = DATAColour, fill = TRUE)
})
predCount <- length(setdiff(colnames(d), c(input$Target, getNonPredictors())))
output$PredictorCount <- renderInfoBox({
infoBox(title = "Predictors", value = predCount, icon = icon("columns"), color = DATAColour, fill = TRUE)
})
ds <- getDataSummary()
ds <- ds[!rownames(ds) %in% getNonPredictors(),]
cont <- getContinuousDebounced()
possCard <- sum(ds$uniqueness > cont[1] & ds$uniqueness <= cont[2] & (ds$text | ds$factor))
highCard <- sum(ds$uniqueness > cont[2] & (ds$text | ds$factor))
output$StringCount <- renderInfoBox({
infoBox(title = "High Cardinality", value = paste0("Certain ", highCard, ", Possible ", possCard), icon = icon("layer-group"), color = DATAColour, fill = TRUE)
})
countnzv <- sum(ds$nzv & !rownames(ds) %in% getNonPredictors())
output$NZVCount <- renderInfoBox({
infoBox(title = "Near-Zero Var.", value = countnzv, icon = icon("adjust"), color = DATAColour, fill = TRUE)
})
ds <- ds[(ds$numeric | ds$date),]
possCont <- sum(ds$uniqueness > cont[1] & ds$uniqueness <= cont[2])
certainCont <- sum(ds$uniqueness > cont[2])
output$ContCount <- renderInfoBox({
infoBox(title = "Continuous", value = paste0("Certain ", certainCont, ", Possible ", possCont), icon = icon("sort-amount-down"), color = DATAColour, fill = TRUE)
})
})
###########################################################################
output$TargetCheck <- renderInfoBox({
d <- getSomeData()
req(isRoleValid(input$Target, d))
col <- d[,input$Target, drop = TRUE]
type <- class(col)
uniqCnt <- length(unique(na.omit(col)))
if (is.numeric(col)) {
isInt <- is.wholenumber(col)
if (isInt & uniqCnt == 2 & nrow(d) > uniqCnt) {
text <- paste("Since there are only", uniqCnt, "unique integer Y values, this is a binary classification problem.")
} else if (isInt & uniqCnt < 11 & nrow(d) > uniqCnt) { #arbitrary 11 used here
text <- paste("Warning: Since there are", uniqCnt, "unique integer Y values, this might be a multi-class classification problem.\nTo make this explicit you may choose to make this column a factor")
} else if (uniqCnt == 1) {
text <- paste("Error: This column has constant data and should be removed. It is not a legitimate target variable.")
} else if (!isInt & uniqCnt/nrow(d) < 0.5) { #arbitrary 0.5 used here
text <- paste("Warning: A column with only", paste0(ceiling(uniqCnt/nrow(d)*100),"%"), "unique numeric values is a suspicious outcome variable for regression")
} else {
text <- paste("This is a regression problem.")
}
} else if ("character" %in% type) {
if (uniqCnt == nrow(d)) {
text <- paste("Warning: This column effectively has text data and should be encoded or used as a row identifier")
} else {
text <- paste("Warning: This column has text data and should be removed or used as a partial row identifier")
}
} else if ("factor" %in% type) {
if (uniqCnt == 2 & nrow(d) > uniqCnt) {
text <- paste("This is a binary classification problem.")
} else if (uniqCnt == nrow(d) ) {
text <- paste("Error: This column effectively has unique text in each row and should be removed or used as a row identifier. \nIt is not a legitimate target variable.")
} else if (uniqCnt/nrow(d) > 0.3) { #arbitrary 0.3 used here
text <- paste("Warning: There are", uniqCnt, "unique Y levels, that is", paste0(ceiling(uniqCnt/nrow(d)*100),"%"),"of the rows. \nThis is a suspicious outcome variable for classification")
} else if (uniqCnt == 1) {
text <- paste("Error: This column has constant data and should be removed. It is not a legitimate target variable.")
} else {
text <- paste0("This is a multinomial (",uniqCnt," levels) classification problem.")
}
} else if ("Date" %in% type) {
text <- paste("Warning: This column has date/time data and should be removed or used as a row identifier. \nIt is not a legitimate outcome variable.")
} else {
text <- paste0("Error: The type is '", type,"'. It is not a legitimate outcome variable.")
}
infoBox(title = "Outcome", value = text, icon = icon("bullseye"), color = DATAColour, fill = TRUE)
})
###########################################################################
output$RatioObs <- renderInfoBox({
d <- getSomePredictorData()
count <- length(colnames(d)) - ifelse(isRoleValid(input$Target, d), 1, 0)
rows <- nrow(getData())
text <- paste0("Observations ", rows,", Predictors ",count, ", Ratio of Obs/Pred ", round(rows/count,1))
infoBox(title = "Ratio", value = text, icon = icon("balance-scale-right"), color = DATAColour, fill = TRUE)
})
###########################################################################
output$StringCount <- renderInfoBox({
ds <- getDataSummary()
ds <- ds[!rownames(ds) %in% getNonPredictors(),]
cont <- getContinuousDebounced()
poss <- sum(ds$uniqueness > cont[1] & ds$uniqueness <= cont[2] & (ds$text | ds$factor))
high <- sum(ds$uniqueness > cont[2] & (ds$text | ds$factor))
infoBox(title = "High Cardinality", value = paste0("Certain ", high, ", Possible ", poss), icon = icon("layer-group"), color = DATAColour, fill = TRUE)
})
###########################################################################
output$NZVCount <- renderInfoBox({
ds <- getDataSummary()
count <- sum(ds$nzv & !rownames(ds) %in% getNonPredictors())
infoBox(title = "Near-Zero Var.", value = count, icon = icon("adjust"), color = DATAColour, fill = TRUE)
})
###########################################################################
output$ContCount <- renderInfoBox({
ds <- getDataSummary()
ds <- ds[!rownames(ds) %in% getNonPredictors() & (ds$numeric | ds$date),]
cont <- getContinuousDebounced()
poss <- sum(ds$uniqueness > cont[1] & ds$uniqueness <= cont[2])
certain <- sum(ds$uniqueness > cont[2])
infoBox(title = "Continuous", value = paste0("Certain ", certain, ", Possible ", poss), icon = icon("sort-amount-down"), color = DATAColour, fill = TRUE)
})
###########################################################################
output$MissObs <- renderInfoBox({
d <- getSomePredictorData() # avoid the hidden vars
req(d)
m <- sum(base::apply(X = d, MARGIN = 1, FUN = function(x) any(is.na(x))))
some <- round(m / dim(d)[1] * 100, 1)
rows <- base::apply(X = d, MARGIN = 1, FUN = function(x) sum(is.na(x))) / ncol(d)
cnt <- sum(rows > input$MissObsThreshold / 100)
heavy <- round(cnt / nrow(d) * 100, 1)
infoBox(title = "Missing Observations", value = paste0("Heavy ", heavy, "%, Some ", some, "%"), icon = icon("align-justify"), color = DATAColour, fill = TRUE)
})
###########################################################################
output$MissVar <- renderInfoBox({
d <- getSomePredictorData()
req(d)
some <- sum(base::apply(X = d, MARGIN = 2, FUN = function(x) any(is.na(x))))
ds <- getDataSummary()
cols <- ds$missingRate > input$MissVarThreshold / 100
heavy <- sum(cols)
infoBox(title = "Missing Predictor Variables", value = paste0("Heavy ", heavy, ", Some ", some), icon = icon("columns"), color = DATAColour, fill = TRUE)
})
###########################################################################
output$MissTarget <- renderInfoBox({
d <- getSomeData()
req(d)
req(isRoleValid(input$Target, d))
some <- round(sum(is.na(d[,input$Target])) / nrow(d) * 100, 1)
infoBox(title = "Missing Outcome Variable", value = paste0(some,"%"), icon = icon("exclamation-triangle"), color = DATAColour, fill = TRUE)
})
###########################################################################
output$DataSummary <- renderUI({
Data <- getSomeData()
summary <- summarytools::dfSummary(Data, graph.magnif = 1.5)
summarytools::view(summary,
method = 'render',
report.title = NA,
headings = FALSE,
bootstrap.css = FALSE,
footnote = NA,
max.tbl.height = 600,
collapse = TRUE,
silent = TRUE
)
})
###########################################################################
output$MissingChart1 <- renderPlotly({
data <- getSomeData()
req(ncol(data) > 0)
sort = input$SortOrder
if (length(sort) > 0 && all(sort %in% colnames(data))) {
data <- data[order(data[,sort]), ]
ylab = paste("Observations in", paste0(sort, collapse = ","), "order")
} else {
ylab = "Observations in natural order"
}
if (input$HideIrrelevant) {
colCounts <- base::colSums(is.na(data))
if (any(colCounts > 0)) {
data <- data[, colCounts > 0, drop = FALSE]
}
}
plot <- visdat::vis_miss(data, cluster = FALSE, sort_miss = FALSE, show_perc = TRUE) +
labs(x = "Variables", title = "Missing values throughout the data", y = ylab) +
coord_flip()
plotly(plot, tooltip = c("variable", "value"))
})
###########################################################################
output$MissingChart2 <- renderPlot({
d <- getSomeData()
req(ncol(d) > 0)
missingCounts(d)
}, bg = "transparent")
###########################################################################
output$MissObservations <- renderText({
d <- getData()
# remove unwanted columns
m <- sum(base::apply(X = d, MARGIN = 1, FUN = function(x) any(is.na(x))))
paste0(m, " (", round(m / dim(d)[1] * 100), "%)")
})
###########################################################################
output$MissVariables <- renderText({
d <- getData()
# remove unwanted columns
m <- sum(base::apply(X = d, MARGIN = 2, FUN = function(x) any(is.na(x))))
paste0(m, " (", round(m / dim(d)[2] * 100), "%)")
})
###########################################################################
output$MissValues <- renderText({
d <- getData()
# remove unwanted columns
m <- sum(is.na(d))
paste0(m, " (", round(m / dim(d)[1] / dim(d)[2] * 100), "%)")
})
# reactive function getMissObsRatios ####
getMissObsRatios <- reactive({
d <- getData()
base::apply(X = d, MARGIN = 1, FUN = function(x) sum(is.na(x))) / ncol(d)
})
###########################################################################
output$HeavyMissObs <- renderText({
cnt <- sum(getMissObsRatios() > input$MissObsThreshold / 100)
prop <- cnt / nrow(getData()) * 100
paste0(cnt, " (", round(prop,1), "%)")
})
###########################################################################
output$HeavyMissVar <- renderText({
d <- getData()
ds <- getDataSummary()
cols <- ds$missingRate > input$MissVarThreshold / 100
cnt <- sum(cols)
prop <- cnt / ncol(d) * 100
paste0(cnt, " (",round(prop,1), "%)")
})
###########################################################################
getTrainedModels <- reactive({
req(length(react$ModelSet) >= 1)
bad <- unlist(lapply(react$ModelSet, FUN = inherits, what = c("character")))
req(sum(!bad) > 0)
react$ModelSet[!bad]
})
###########################################################################
getTimings <- reactive({
d <- getTrainData()
thousand <- sample(nrow(d), size = 1000, replace = TRUE)
d <- d[thousand, ]
timing <- c()