-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.R
1316 lines (1078 loc) · 46.3 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
function(input, output, session) {
observe(
showModal(modalDialog(
title = "Important message",
"This app may take up to 2 minutes to load on first start-up. Thank you for your patience. We are working on improvements to be released soon.",
easyClose = TRUE))
)
# Functions ---------------------------------------------------------------
# Column Subset Crosstab Generator
xtab.col.subset <- function(table, colstring = col.headers) {
cols <- c(varsXAlias(), str_subset(colnames(table), paste0("^", colstring)))
table[, ..cols]
}
# xtab.edit.samplecnt <- function(dt, thresholdcnt) {
# # dt <- copy(xtabstyletable)
# edit.ind <- as.data.table(which(dt < thresholdcnt, arr.ind = T))
# edit.rows <- unique(edit.ind$row)
# dt[edit.rows, (colnames(dt)[2:length(colnames(dt))]) := 1]
# }
xtab.join.samplecnt <- function(xtabcleandt, dttype, varsXAlias) {
dt.data <- xtabcleandt[[dttype]]
dt.sort.rows <- dt.data[[varsXAlias]]
dt.style <- copy(xtabcleandt[['sample_count']])
# alter dt.style, update rows containing < 30
# dt.style <- xtab.edit.samplecnt(dt.style, 30)
colnames(dt.style)[2:length(colnames(dt.style))] <- paste0(colnames(dt.style)[2:length(colnames(dt.style))], "_sc")
dt <- base::merge(dt.data, dt.style, by = varsXAlias)
dt[, var1.sort := factor(base::get(varsXAlias), levels = dt.sort.rows)]
dt <- dt[order(var1.sort)][, var1.sort := NULL]
}
xtab.tblMOE.join.samplecnt <- function(xtabcleantblMOEdt, xtabcleandt, dttype, varsXAlias) {
dt.data <- xtabcleantblMOEdt
dt.style <- copy(xtabcleandt[['sample_count']])
dt.sort.rows <- dt.data[[varsXAlias]]
idx <- 2:ncol(dt.style)
colnames(dt.style)[idx] <- paste0(letters[1:(ncol(dt.style)-1)], "_", colnames(dt.style)[idx], "_sc")
new.cols <- paste0(colnames(dt.style)[idx], "2")
cols <- colnames(dt.style)[idx]
col2order <- sort(c(cols, new.cols))
dt.style[, (new.cols) := mapply(function(x) replicate(1, .SD[[x]]), cols, SIMPLIFY = F)]
setcolorder(dt.style, c(varsXAlias, col2order))
# alter dt.style, update rows containing < 30
# dt.style <- xtab.edit.samplecnt(dt.style, 30)
dt <- base::merge(dt.data, dt.style, by = varsXAlias)
dt[, var1.sort := factor(base::get(varsXAlias), levels = dt.sort.rows)]
dt <- dt[order(var1.sort)][, var1.sort := NULL]
}
xtab.create.DT <- function(atable, moe = c(TRUE, FALSE), acontainer, indices2hide, maxyvals, sc.cols) {
colors <- list(ltgrey = '#bdbdc3', dkgrey = '#343439')
if (moe == TRUE) {
defs <- list(list(className = "dt-head-center dt-center", targets = "_all"),# DT CRAN hack
list(visible = F, targets = indices2hide)) # DT's column index starts at 0 not 1
} else {
defs <- list(list(visible = F, targets = indices2hide)) # DT's column index starts at 0 not 1
}
DT::datatable(atable,
# caption = acaption,
container = acontainer,
rownames = FALSE,
options = list(bFilter=0,
columnDefs = defs) # DT's column index starts at 0 not 1
) %>%
formatStyle(columns = 2:maxyvals,
valueColumns = sc.cols,
color = styleInterval(c(30), c(colors$ltgrey, colors$dkgrey)))
}
dt.container.dtstyle <- function(atable, xvaralias, yvaralias) {
sc.cols <- str_subset(colnames(atable), "_sc")
num.disp.cols <- ncol(atable) - length(sc.cols)
htmltools::withTags(table(
class = 'display',
thead(
tr(
th(class = 'dt-center', rowspan = 2, xvaralias),
th(class = 'dt-center', colspan = (num.disp.cols-1), yvaralias)
), # end tr
tr(
lapply(colnames(atable)[2:num.disp.cols], th)
) # end tr
) # end thead
) # end table
) # end withTags
}
dt.container.tblMOE.dtstyle <- function(atable, xvaralias, yvaralias, tbltype = c("share", "estimate", "median")) {
# ifelse(tbltype == "share", tbltype <- "Share", tbltype <- "Total")
if (tbltype == "share") {
tbltype <- "Share"
} else if (tbltype == "estimate") {
tbltype <- "Total"
} else {
tbltype <- "median"
}
exc.cols <- str_subset(colnames(atable), paste(xvaralias, "_MOE|_sc.*", sep = "|"))
yval.labels <- setdiff(colnames(atable), exc.cols)
sc.cols <- str_subset(colnames(atable), "_sc.*")
num.disp.cols <- ncol(atable) - length(sc.cols)
if (tbltype == "Share" |tbltype == "Total") {
htmltools::withTags(table(
class = 'display',
thead(
tr(
th(class = 'dt-center', rowspan = 3, xvaralias),
th(class = 'dt-center', colspan = (num.disp.cols-1), yvaralias)
), # end tr
tr(
lapply(yval.labels, function(x) th(class = 'dt-center', colspan = 2, x))
), # end tr
tr(
lapply(rep(c(tbltype, "Margin of Error"), (num.disp.cols-1)/2), function(x) th(style = "font-size:12px", x))
) # end tr
) # end thead
) # end table
) # end withTags
} else {
htmltools::withTags(table(
class = 'display',
thead(
tr(
th(class = 'dt-center', rowspan = 2, xvaralias),
th(class = 'dt-center', colspan = (num.disp.cols-1), yvaralias)
), # end tr
# tr(
# lapply(yval.labels, function(x) th(class = 'dt-center', colspan = 2, x))
# ), # end tr
tr(
lapply(rep(c(tbltype, "Margin of Error"), (num.disp.cols-1)/2), function(x) th(style = "font-size:12px", x))
) # end tr
) # end thead
) # end table
) # end withTags
}
}
# Crosstab Generator Selection --------------------------------------------
xtab.variable.tbl <-eventReactive(input$xtab_dataset,{
# filter variables table by survey year
if(input$xtab_dataset=='2017/2019'){
survey_year_name='2019'
}
else{
survey_year_name=input$xtab_dataset
}
variables.lu[survey_year == survey_year_name, ]
})
# show/hide vars definition
observe({
onclick("xtabXtoggleAdvanced",
toggle(id = "xtabXAdvanced", anim = TRUE))
onclick("xtabYtoggleAdvanced",
toggle(id = "xtabYAdvanced", anim = TRUE))
})
output$xtab_xcol_det <- renderText({
xvar.det <- xtab.variable.tbl()[variable %in% input$xtab_xcol, .(detail)]
unique(xvar.det$detail)
})
output$xtab_ycol_det <- renderText({
yvar.det <- xtab.variable.tbl()[variable %in% input$xtab_ycol, .(detail)]
unique(yvar.det$detail)
})
# X and Y Categories ----------------------------------------------------------
xtab_cat_list <- reactive({
# find unique categories based on dataset
ifelse(input$xtab_dataset == '2017/2019', d <- c('2017', '2019'), d <- '2021')
v <- variables.lu[survey_year %in% d, ]
cat <- unique(v$category)
})
output$ui_xtab_xcat <- renderUI({
selectInput('xtab_xcat',
'Category',
xtab_cat_list())
})
output$ui_xtab_ycat <- renderUI({
# find unique categories based on dataset
selectInput('xtab_ycat',
'Category',
xtab_cat_list())
})
# Update X and Y Categories -----------------------------------------------
# update x and y cateogries
observeEvent(input$xtab_xcat, {
move.var <- 'Reason for leaving previous residence'
hh.var <- 'Household'
move.choices <- c(hh.var, move.var)
x <- input$xtab_xcat
y <- input$xtab_ycat
if (x == move.var) {
# filter to two options
y.choices <- move.choices
} else if ((!(x %in% move.choices) & (y == hh.var))) {
# exclude 'Reason...'
y.choices <- xtab_cat_list()[!(xtab_cat_list() %in% move.var)]
} else if (x == hh.var) {
# default options
y.choices <- xtab_cat_list()[!(xtab_cat_list() %in% "None")]
} else if (x != move.var & y != move.var) {
# exclude 'Reason...'
y.choices <- xtab_cat_list()[!(xtab_cat_list() %in% move.var)]
} else {
# default options
y.choices <- xtab_cat_list()[!(xtab_cat_list() %in% "None")]
}
updateSelectInput(session, "xtab_ycat",
label = "Category",
selected = y,
choices = y.choices)
})
observeEvent(input$xtab_ycat, ignoreInit = TRUE, {
move.var <- 'Reason for leaving previous residence'
hh.var <- 'Household'
move.choices <- c(hh.var, move.var)
x <- input$xtab_xcat
y <- input$xtab_ycat
if (y == move.var) {
# filter to two options
x.choices <- move.choices
} else if (!(y %in% move.choices)) {
# exclude only 'Reason...'
x.choices <- xtab_cat_list()[!(xtab_cat_list() %in% move.var)]
} else if (y == hh.var) {
# default options
x.choices <- xtab_cat_list()[!(xtab_cat_list() %in% "None")]
} else {
# default options
x.choices <- xtab_cat_list()[!(xtab_cat_list() %in% "None")]
}
updateSelectInput(session, "xtab_xcat",
label = "Category",
selected = x,
choices = x.choices)
})
# variable X alias list
varsListX <- reactive({
v <- xtab.variable.tbl()
t <- v[category %in% input$xtab_xcat & dtype != 'fact', ]
vars.raw <- as.list(unique(t$variable))
vars.list <- setNames(vars.raw, as.list(unique(t$variable_name)))
})
# variable Y alias list
varsListY <- reactive({
v <- xtab.variable.tbl()
t <- v[category %in% input$xtab_ycat, ]
vars.raw <- as.list(unique(t$variable))
vars.list <- setNames(vars.raw, as.list(unique(t$variable_name)))
})
# variable X alias
varsXAlias <- eventReactive(input$xtab_go, {
v <- xtab.variable.tbl()
xvar.alias <- v[variable %in% input$xtab_xcol, .(variable_name)]
unique(xvar.alias$variable_name)
})
# variable Y alias
varsYAlias <- eventReactive(input$xtab_go, {
v <- xtab.variable.tbl()
yvar.alias <- v[variable %in% input$xtab_ycol, .(variable_name)]
unique(yvar.alias$variable_name)
})
# return values associated with category selected
output$ui_xtab_xcol <- renderUI({
selectInput('xtab_xcol',
'Variable',
varsListX())
})
# return values associated with category selected
output$ui_xtab_ycol <- renderUI({
ifelse(length(varsListY()) == 1, y <- varsListY(), y <- varsListY()[2])
selectInput('xtab_ycol',
'Variable',
varsListY(),
selected = y)
})
xtab.values.tbl <-eventReactive(input$xtab_dataset,{
if(input$xtab_dataset=='2017/2019'){
survey_year_name='2019'
}
else{
survey_year_name=input$xtab_dataset
}
values.lu[survey_year == survey_year_name,]
})
xtabXValues <- eventReactive(input$xtab_go, {
# survey_year?
dt <- xtab.values.tbl()[variable %in% input$xtab_xcol, ][order(value_order)] # return dt
})
xtabYValues <- eventReactive(input$xtab_go, {
dt <- xtab.values.tbl()[variable %in% input$xtab_ycol, ][order(value_order)]
v <- as.vector(dt$value_text) # return vector
})
xtabCaption <- eventReactive(input$xtab_go, {
if (input$xtab_fltr_sea == T) {
cap <- "Seattle results"
} else {
cap <- "Regional results"
}
return(cap)
})
output$ui_xtab_res_type_title <- renderUI({
h4(xtabCaption())
})
# Crosstab Generator data wrangling ---------------------------------------
xtabTableType <- eventReactive(input$xtab_go, {
v <- xtab.variable.tbl()
select.vars <- v[variable %in% c(input$xtab_xcol, input$xtab_ycol), ]
select.tables<-select.vars$table_name
select.wts<-select.vars$weight_name
select.priority<-select.vars$weight_priority
weight_name<- select.wts[which.min(select.priority)]
dtypes <- as.vector(unique(select.vars$dtype))
if('Trip' %in% select.tables){
res<-table_names[['Trip']]
} else if('Person' %in% select.tables){
res<- table_names[['Person']]
}else{
res<-table_names[['Household']]
}
if('fact' %in% dtypes){
type<- 'fact'
}
else{
type<-'dimension'
}
return(list(WeightName=weight_name, Type=type, Table_Name=res))
})
# return list of tables subsetted by value types
xtabTable <- eventReactive(input$xtab_go, {
tbl_name <- xtabTableType()$Table_Name
type <- xtabTableType()$Type
data
if (input$xtab_dataset == '2017/2019')
{
survey_yr = "2017_2019"
}
else{
survey_yr = input$xtab_dataset
}
data_for_xtab <-
get_hhts(
survey = survey_yr,
level = tbl_name,
vars = c("seattle_home", input$xtab_xcol, input$xtab_ycol)
) %>% setDT()
if (input$xtab_fltr_sea == T) {
data_for_xtab[seattle_home == "Home in Seattle"]
}
if (type=='fact') {
crosstab <-
hhts_median(
data_for_xtab,
input$xtab_ycol,
group_vars = input$xtab_xcol,
incl_na = FALSE
) %>% rename('median' = ends_with('median'))%>% rename('MOE'=ends_with('MOE')) %>%
rename(sample_count= sample_size)
crosstab <- crosstab%>% select(input$xtab_xcol, "median", "MOE", 'sample_count')
}
else{
crosstab <- hhts_count(data_for_xtab,
group_vars = c(input$xtab_xcol, input$xtab_ycol),
incl_na = FALSE)
setnames(crosstab, old=c('count', 'count_moe', 'share', 'share_moe', 'sample_size'), new=c("estimate", "estMOE", "share", "MOE", 'sample_count'))
crosstab <- crosstab%>% select(input$xtab_xcol, input$xtab_ycol, "estimate", "estMOE", "share", "MOE", 'sample_count')%>%
pivot_wider(names_from=input$xtab_ycol, values_from=c("estimate", "estMOE", "share", "MOE", 'sample_count'))%>% setDT()
}
xvals <- xtabXValues()[, .(value_order, value_text)]
crosstab <-
base::merge(crosstab, xvals, by.x = input$xtab_xcol, by.y = 'value_text')
setorder(crosstab, value_order)
setnames(crosstab, input$xtab_xcol, varsXAlias(), skip_absent = TRUE)
xtab.crosstab <- partial(xtab.col.subset, table = crosstab)
if (type == 'dimension') {
column.headers <- col.headers
} else if (type == 'fact') {
column.headers <- col.headers.facts
}
dt.list <- map(as.list(column.headers), xtab.crosstab)
names(dt.list) <- column.headers
return(dt.list)
})
# clean xtabTable()
xtabTableClean <- reactive({
dt.list <- xtabTable()
# yv <- xtabYValues()
xa <- varsXAlias()
# col.headers <- lapply(col.headers, function(x) paste0(x, "_")) %>% unlist
# regex <- paste(col.headers, collapse = "|")
if (xtabTableType()$Type == 'dimension') {
yv <- xtabYValues()
col.headers <- lapply(col.headers, function(x) paste0(x, "_")) %>% unlist
regex <- paste(col.headers, collapse = "|")
# evaluates for NA columns & rows, and excludes it
for (i in 1:length(dt.list)) {
dt.list[[i]] <- dt.list[[i]][!(base::get(eval(xa)) %in% "")]
new.colnames <- str_extract(colnames(dt.list[[i]])[2:length(colnames(dt.list[[i]]))], paste0("(?<=", regex, ").+")) # includes blank
if (any(is.na(new.colnames))) { # if contains any NA columns
nonna.new.colnames <- str_subset(new.colnames, ".")
setnames(dt.list[[i]], colnames(dt.list[[i]]), c(xa, new.colnames)) # blank becomes NA
keep.cols <- colnames(dt.list[[i]])[!is.na(colnames(dt.list[[i]]))]
dt.list[[i]] <- dt.list[[i]][, ..keep.cols]
if (length(yv) != 0) {
yv.subset <- yv[yv %in% nonna.new.colnames] # only account for yv vals that exist in dt
setcolorder(dt.list[[i]], c(xa, yv.subset))
}
} else {
setnames(dt.list[[i]], colnames(dt.list[[i]]), c(xa, new.colnames))
if (!is.null(yv)) {
yv.subset <- yv[yv %in% new.colnames] # are all yv vals accounted for in new.colnames
setcolorder(dt.list[[i]], c(xa, yv.subset))
}
}
}
} else if (xtabTableType()$Type == 'fact') {
new.colnames.fact <- c("Median" = "median", "Sample Count" = "sample_count")
for (i in 1:length(dt.list)) {
# set colnames for median, sample count
if (names(dt.list[i]) %in% new.colnames.fact) {
setnames(dt.list[[i]],
names(dt.list[i]),
names(new.colnames.fact[new.colnames.fact %in% names(dt.list[i])]), skip_absent = TRUE)
} else {
next
}
}
}
return(dt.list)
})
create.table.joining.moe <- function(valuetable, moetable, xalias, xvalues) {
# This is function is for Dimension related tables
dtcols <- colnames(valuetable)[2:ncol(valuetable)]
cols.order <- c()
for (acol in dtcols) {
moe.col <- paste0(acol, "_MOE")
cols.order <- append(cols.order, c(acol, moe.col))
}
colnames(moetable)[2:ncol(moetable)] <- paste0(colnames(moetable)[2:ncol(moetable)], "_MOE")
dt.sm <- base::merge(valuetable, moetable, by = xalias)
dt.sm[, var1.sort := factor(base::get(eval(xalias)), levels = xvalues$value_text)]
dt.sm <- dt.sm[order(var1.sort)][, var1.sort := NULL]
order.colnames <- c(xalias, cols.order)
dt.sm <- dt.sm[, ..order.colnames]
}
# create separate table of shares alongside margin of errors
xtabTableClean.ShareMOE <- reactive({
xa <- varsXAlias()
xvals <- xtabXValues()[, .(value_order, value_text)]
dt.s <- xtabTableClean()[['share']]
dt.m <- xtabTableClean()[['MOE']]
dt.sm <- create.table.joining.moe(dt.s, dt.m, xa, xvals)
})
# create separate table of estimates alongside margin of errors
xtabTableClean.EstMOE <- reactive({
xa <- varsXAlias()
xvals <- xtabXValues()[, .(value_order, value_text)]
dt.s <- xtabTableClean()[['estimate']]
dt.m <- xtabTableClean()[['estMOE']]
dt.sm <- create.table.joining.moe(dt.s, dt.m, xa, xvals)
})
# create separate table of median (for fact related tables) alongside margin of errors
xtabTableClean.medianMOE <- reactive({
xa <- varsXAlias()
xvals <- xtabXValues()[, .(value_order, value_text)]
dt.s <- xtabTableClean()[['median']]
dt.m <- xtabTableClean()[['MOE']]
dt <- base::merge(dt.s, dt.m, by = xa)
dt[, var1.sort := factor(base::get(eval(xa)), levels = xvals$value_text)]
dt.sm <- dt[order(var1.sort)][, var1.sort := NULL]
})
xtabTableClean.DT.medianMOE <- reactive({
t <- copy(xtabTableClean.medianMOE())
t[, MOE := lapply(.SD, function(x) prettyNum(round(x, 2), big.mark = ",", preserve.width = "none")), .SDcols = 'MOE']
t[, MOE := lapply(.SD, function(x) paste0("+/-", as.character(x))), .SDcols = 'MOE']
})
xtabTableClean.DT.ShareMOE <- reactive({
t <- copy(xtabTableClean.ShareMOE())
moe.cols <- str_subset(colnames(t), "_MOE$")
t[, (moe.cols) := lapply(.SD, function(x) round(x*100, 1)), .SDcols = moe.cols]
t[, (moe.cols) := lapply(.SD, function(x) paste0("+/-", as.character(x), "%")), .SDcols = moe.cols]
for(j in seq_along(t)){
set(t, i = which(t[[j]] == "+/-NA%"), j=j, value="")
}
return(t)
})
xtabTableClean.DT.EstMOE <- reactive({
t <- copy(xtabTableClean.EstMOE())
moe.cols <- str_subset(colnames(t), "_MOE$")
t[, (moe.cols) := lapply(.SD, function(x) prettyNum(round(x, 0), big.mark = ",", preserve.width = "none")), .SDcols = moe.cols]
t[, (moe.cols) := lapply(.SD, function(x) paste0("+/-", as.character(x))), .SDcols = moe.cols]
for(j in seq_along(t)){
set(t, i = which(t[[j]] == "+/-NA"), j=j, value="")
}
return(t)
})
# Crosstab Generator Visuals ----------------------------------------------
create.table.vistable.moe <- function(valuetable, moetable, xalias, xvalues) {
msrcols <- colnames(valuetable)[!(colnames(valuetable) %in% xalias)]
dts <- melt.data.table(valuetable, id.vars = xalias, measure.vars = msrcols, variable.name = "value", value.name = "result")
if (xtabTableType()$Type == 'dimension') {
dtm <- melt.data.table(moetable, id.vars = xalias, measure.vars = msrcols, variable.name = "value", value.name = "result_moe")
dt <- base::merge(dts, dtm, by = c(xalias, "value"))
setnames(dt, xalias, "group")
} else {
dt <- base::merge(dts, moetable, by = c(xalias))
setnames(dt, c(xalias, 'MOE'), c("group", "result_moe"))
}
if (nrow(xvalues) != 0) {
dt[, group := factor(group, levels = xvalues$value_text)][, group := fct_explicit_na(group, "No Response")]
dt <- dt[order(group)]
} else {
dt[, group := factor(group)]
}
return(dt)
}
xtabVisTable.EstMOE <- reactive({
xa <- varsXAlias()
xvals <- xtabXValues()[, .(value_order, value_text)]
dt.s <- xtabTableClean()[['estimate']]
dt.m <- xtabTableClean()[['estMOE']]
dt <- create.table.vistable.moe(dt.s, dt.m, xa, xvals)
})
xtabVisTable.ShareMOE <- reactive({
xa <- varsXAlias()
xvals <- xtabXValues()[, .(value_order, value_text)]
dt.s <- xtabTableClean()[['share']]
dt.m <- xtabTableClean()[['MOE']]
dt <- create.table.vistable.moe(dt.s, dt.m, xa, xvals)
})
xtabVisTable.medianMOE <- reactive({
xa <- varsXAlias()
xvals <- xtabXValues()[, .(value_order, value_text)]
dt.s <- xtabTableClean()[['median']]
dt.m <- xtabTableClean()[['MOE']]
dt <- create.table.vistable.moe(dt.s, dt.m, xa, xvals)
})
xtabVisTable <- reactive({
dt.list <- xtabTableClean()
xvals <- xtabXValues()[, .(value_order, value_text)]
visdt.list <- NULL
for (i in 1:length(dt.list)) {
idcol <- varsXAlias()
msrcols <- colnames(dt.list[[i]])[!(colnames(dt.list[[i]]) %in% idcol)]
varcol <- "value"
t <- melt.data.table(dt.list[[i]], id.vars = idcol, measure.vars = msrcols, variable.name = "value", value.name = "result")
t[, type := names(dt.list[i])]
setnames(t, idcol, "group")
if (nrow(xvals) != 0) {
t[, group := factor(group, levels = xvals$value_text)][, group := fct_explicit_na(group, "No Response")]
t <- t[order(group)]
} else {
t[, group := factor(group)]
}
visdt.list[[names(dt.list[i])]]<- t
}
return(visdt.list)
})
output$xtab_vis <- renderPlotly({
xlabel <- varsXAlias() # first dim
ylabel <- varsYAlias() # second dim
geog.caption <- xtabCaption()
survey_year_name <- input$xtab_dataset
source.string <- paste(survey_year_name, "Household Travel Survey")
if (xtabTableType()$Type == 'dimension') {
if (is.null(input$xtab_dtype_rbtns)) return(NULL)
dttype <- input$xtab_dtype_rbtns
dttype.label <- names(dtype.choice.xtab[dtype.choice.xtab == dttype])
if (dttype %in% c("sample_count", "estimate", "share", "MOE", "N_HH")) {
dt <- xtabVisTable()[[dttype]]
} else {
if (dttype == "share_with_MOE") dt <- xtabVisTable.ShareMOE()
if (dttype == "estimate_with_MOE") dt <- xtabVisTable.EstMOE()
}
l <- length(unique(dt$value))
if (dttype == 'share') {
ifelse(l > 10, p <- xtab.plot.bar.pivot(dt, "percent", xlabel, ylabel, dttype.label, geog.caption, source.string), p <- xtab.plot.bar(dt, "percent", xlabel, ylabel, dttype.label, geog.caption, source.string))
return(p)
} else if (dttype %in% c('estimate', 'sample_count', 'N_HH')) {
ifelse(l > 10, p <- xtab.plot.bar.pivot(dt, "nominal", xlabel, ylabel, dttype.label, geog.caption, source.string), p <- xtab.plot.bar(dt, "nominal", xlabel, ylabel, dttype.label, geog.caption, source.string))
return(p)
} else if (dttype %in% c('share_with_MOE')) {
ifelse(l > 10, p <- xtab.plot.bar.moe.pivot(dt, "percent", xlabel, ylabel, geog.caption, source.string), p <- xtab.plot.bar.moe(dt, "percent", xlabel, ylabel, geog.caption, source.string))
return(p)
} else if (dttype %in% c('estimate_with_MOE')) {
ifelse(l > 10, p <- xtab.plot.bar.moe.pivot(dt, "nominal", xlabel, ylabel, geog.caption, source.string), p <- xtab.plot.bar.moe(dt, "nominal", xlabel, ylabel, geog.caption, source.string))
return(p)
} else {
return(NULL)
}
} else { # if xtabTableType()$Type == 'fact'
if (is.null(input$xtab_dtype_rbtns_fact)) return(NULL)
dttype <- input$xtab_dtype_rbtns_fact
dttype.label <- names(dtype.choice.xtab.facts[dtype.choice.xtab.facts == dttype])
if (dttype %in% c("sample_count", "median", "MOE", "N_HH")) {
dt <- xtabVisTable()[[dttype]]
} else { #if (dttype == "median_with_MOE")
dt <- xtabVisTable.medianMOE()
}
if (dttype %in% c("sample_count", "median", "N_HH")) {
p <- xtab.plot.bar.fact(dt, "nominal", xlabel, ylabel, dttype.label, geog.caption, input$xtab_dataset)
return(p)
} else { # median_with_MOE
p <- xtab.plot.bar.fact.moe(dt, "nominal", xlabel, ylabel, dttype.label, geog.caption, input$xtab_dataset)
return(p)
}
} # end of if/else dim or fact
})
# Crosstab Generator Table Rendering --------------------------------------------
xtabDtypeBtns <- eventReactive(input$xtab_go, {
# This reactive will change the display of 'Summary Types' radio buttons
# depending on whether it is a dimension or fact related table
if (xtabTableType()$Type == 'dimension') {
btns <- wellPanel(
radioButtons("xtab_dtype_rbtns",
label = strong("Summary Types"),
choices = dtype.choice.xtab
),
div(p("Shares are based on rowwise totals."), style = 'font-size: 85%')
) # end wellPanel
} else if (xtabTableType()$Type == 'fact') {
btns <- wellPanel(
radioButtons("xtab_dtype_rbtns_fact",
label = strong("Summary Types"),
choices = dtype.choice.xtab.facts
)
) # end wellPanel
}
return(btns)
})
output$ui_xtab_dtype_rbtns <- renderUI(
xtabDtypeBtns()
)
output$xtab_tbl <- DT::renderDataTable({
if ((xtabTableType()$Type == 'dimension')) {
if (is.null(input$xtab_dtype_rbtns)) return(NULL)
dttype <- input$xtab_dtype_rbtns
if (dttype %in% c("sample_count", "estimate", "estMOE", "share", "MOE", "N_HH")) {
# This if/else chunk joins sample count to the table of choice with the purpose
# of greying out values where sample counts are low.
dt <- xtab.join.samplecnt(xtabTableClean(), dttype, varsXAlias())
sc.cols <- str_which(colnames(dt), "_sc")
sc.idx <- sc.cols - 1
disp.col.max <- length(setdiff(colnames(dt), str_subset(colnames(dt), "_sc")))
} else {
if (dttype %in% c("share_with_MOE")) {
dt <- xtab.tblMOE.join.samplecnt(xtabTableClean.DT.ShareMOE(), xtabTableClean(), dttype, varsXAlias())
} else if (dttype %in% c("estimate_with_MOE")) {
dt <- xtab.tblMOE.join.samplecnt(xtabTableClean.DT.EstMOE(), xtabTableClean(), dttype, varsXAlias())
}
moe.colnms <- str_subset(colnames(dt)[2:ncol(dt)], "_MOE")
sc.colnms <- str_subset(colnames(dt)[2:ncol(dt)], "_sc.*")
cols.fmt <- setdiff(colnames(dt)[2:ncol(dt)], c(moe.colnms, sc.colnms))
sc.cols <- str_which(colnames(dt), "_sc.*")
sc.idx <- sc.cols - 1
disp.col.max <- length(setdiff(colnames(dt), str_subset(colnames(dt), "_sc.*")))
}
sketch.dtstyle <- dt.container.dtstyle(dt, varsXAlias(), varsYAlias())
if (dttype == 'share') {
xtab.create.DT(dt, moe = F, sketch.dtstyle, sc.idx, disp.col.max, sc.cols) %>%
formatPercentage(colnames(dt)[2:disp.col.max], 1)
} else if (dttype == 'estimate') {
xtab.create.DT(dt, moe = F, sketch.dtstyle, sc.idx, disp.col.max, sc.cols) %>%
formatRound(colnames(dt)[2:disp.col.max], 0)
} else if (dttype == 'sample_count') {
xtab.create.DT(dt, moe = F, sketch.dtstyle, sc.idx, disp.col.max, sc.cols) %>%
formatRound(colnames(dt)[2:disp.col.max], 0)
} else if (dttype == 'share_with_MOE') {
sketch.dtstyle.exp <- dt.container.tblMOE.dtstyle(dt, varsXAlias(), varsYAlias(), "share")
xtab.create.DT(dt, moe = T, sketch.dtstyle.exp, sc.idx, disp.col.max, sc.cols) %>%
formatPercentage(cols.fmt, 1)
} else if (dttype == 'estimate_with_MOE') {
sketch.dtstyle.exp <- dt.container.tblMOE.dtstyle(dt, varsXAlias(), varsYAlias(), "estimate")
xtab.create.DT(dt, moe = T, sketch.dtstyle.exp, sc.idx, disp.col.max, sc.cols) %>%
formatRound(cols.fmt, 0)
}
} else if ((xtabTableType()$Type == 'fact')) {
if (is.null(input$xtab_dtype_rbtns_fact)) return(NULL)
dttype <- input$xtab_dtype_rbtns_fact
if (dttype %in% c("median", "sample_count")) {
# This if/else chunk joins sample count to the table of choice with the purpose
# of greying out values where sample counts are low.
dt <- xtab.join.samplecnt(xtabTableClean(), dttype, varsXAlias())
sc.cols <- str_which(colnames(dt), "_sc")
sc.idx <- sc.cols - 1
disp.col.max <- length(setdiff(colnames(dt), str_subset(colnames(dt), "_sc")))
} else {
if (dttype %in% c("median_with_MOE")) {
dt <- xtab.tblMOE.join.samplecnt(xtabTableClean.DT.medianMOE(), xtabTableClean(), dttype, varsXAlias())
}
moe.colnms <- str_subset(colnames(dt)[2:ncol(dt)], "MOE")
sc.colnms <- str_subset(colnames(dt)[2:ncol(dt)], "_sc.*")
cols.fmt <- setdiff(colnames(dt)[2:ncol(dt)], c(moe.colnms, sc.colnms))
sc.cols <- str_which(colnames(dt), "_sc.*")
sc.idx <- sc.cols - 1
disp.col.max <- length(setdiff(colnames(dt), str_subset(colnames(dt), "_sc.*")))
}
sketch.dtstyle <- dt.container.dtstyle(dt, varsXAlias(), varsYAlias())
if (dttype == 'median') {
xtab.create.DT(dt, moe = F, sketch.dtstyle, sc.idx, disp.col.max, sc.cols) %>%
formatRound(colnames(dt)[2:disp.col.max], 2)
} else if (dttype == 'sample_count') {
xtab.create.DT(dt, moe = F, sketch.dtstyle, sc.idx, disp.col.max, sc.cols) %>%
formatRound(colnames(dt)[2:disp.col.max], 0)
} else if (dttype == 'median_with_MOE') {
sketch.dtstyle.exp <- dt.container.tblMOE.dtstyle(dt, varsXAlias(), varsYAlias(), "median")
xtab.create.DT(dt, moe = T, sketch.dtstyle.exp, sc.idx, disp.col.max, sc.cols) %>%
formatRound(cols.fmt, 2)
}
}
})
output$ui_xtab_tbl <- renderUI({
div(DT::dataTableOutput('xtab_tbl'), style = 'font-size: 95%; width: 85%', class = 'visual-display', )
})
output$ui_xtab_vis <- renderUI({
# if (xtabTableType()$Type == 'dimension') {
# plotlyOutput("xtab_vis", width = "85%")
# } else {
# div(p('Results not available. This functionality is in progress.'),
# style = 'display: flex; justify-content: center; align-items: center; margin-top: 5em;')
# }
div(plotlyOutput("xtab_vis", width = "85%"), class = 'visual-display')
})
# Crosstab Generator Download ---------------------------------------------
# Enable/Disable download button
v <- reactiveValues(xtabxcol = NULL,
xtabycol = NULL,
xtabgo = 0,
xtabfltrsea = F)
observeEvent(input$xtab_go, {
v$xtabxcol <- input$xtab_xcol
v$xtabycol <- input$xtab_ycol
v$xtabgo <- v$xtabgo + 1
v$xtabfltrsea <- input$xtab_fltr_sea
})
observe({
if (v$xtabgo == 0 || (v$xtabycol != input$xtab_ycol) || (v$xtabxcol != input$xtab_xcol) || (v$xtabfltrsea != input$xtab_fltr_sea)) {
disable("xtab_download")
} else if (v$xtabgo > 0) {
enable("xtab_download")
}
})
xtabDownloadOutput <- reactive({
dtlist <- copy(xtabTableClean())
t <- dtlist[['sample_count']]
data.type <- xtabTableType()$Type
geog <- xtabCaption()
if (data.type == 'dimension') {
tsm <- copy(xtabTableClean.DT.ShareMOE())
tem <- copy(xtabTableClean.DT.EstMOE())
# Format tsm, every other column as string starting at index 2
nums <- seq(1, length(colnames(tsm)))
evens <- unlist(lapply(nums, function(x) x %%2 ==0))
ind <- nums[evens]
cols.to.str <- colnames(tsm)[ind]
tsm[, (cols.to.str) := lapply(.SD, function(x) paste0(as.character(round(x*100, 1)), '%')), .SDcols = cols.to.str]
# Format tem, every other column as string starting at index 2
cols.to.prettynum <- colnames(tem)[ind]
tem[, (cols.to.prettynum) := lapply(.SD, function(x) prettyNum(round(x), big.mark = ",")), .SDcols = cols.to.prettynum]
for(j in seq_along(tsm)){
set(tsm, i = which(tsm[[j]] == "NA%"), j=j, value="")
}
for(j in seq_along(tem)){
set(tem, i = which(tem[[j]] == "NA"), j=j, value="")
}
tsm[, `Result Type` := geog]
tem[, `Result Type` := geog]
t[, `Result Type` := geog]
tbllist <- list("About" = readme.dt,
"Share with Margin of Error" = tsm,
"Total with Margin of Error" = tem,
"Sample Count" = t)
} else if (data.type == 'fact') {
# join median/MOE with sample count
tmm <- copy(xtabTableClean.DT.medianMOE())
tjoin <- tmm[t, on = varsXAlias()]
tj <- tjoin[, median := lapply(.SD, function(x) round(x, 2)), .SDcols = 'Median'
][, `Sample Count`:= lapply(.SD, function(x) prettyNum(x, big.mark = ",")), .SDcols = "Sample Count"
][, `Result Type` := geog]
setnames(tj, "MOE", "Margin of Error (median)")
tbllist <- list("About" = readme.dt,
"median with Margin of Error" = tj)
}
return(tbllist)
})
output$xtab_download <- downloadHandler(
filename = function() {
paste0("HHSurvey", input$xtab_dataset, "_", varsXAlias(), "_by_", varsYAlias(), "_", xtabCaption(), ".xlsx")
},
content = function(file) {
write.xlsx(xtabDownloadOutput(), file)
}
)
# Simple Table ------------------------------------------------------------
# show/hide vars definition
observe({
onclick("stabXtoggleAdvanced",
toggle(id = "stabXAdvanced", anim = TRUE))
})
stab.variable.tbl<-eventReactive(input$stab_dataset,{
# filter variables table by survey year
if(input$stab_dataset=='2017/2019'){
survey_year_name='2019'
}
else{
survey_year_name=input$stab_dataset
}
variables.lu[survey_year == survey_year_name, ]
})
stab.values.tbl<-eventReactive(input$stab_dataset,{
# filter variables table by survey year
if(input$stab_dataset=='2017/2019'){
survey_year_name='2019'
}
else{
survey_year_name=input$stab_dataset
}
values.lu[survey_year==survey_year_name, ]
})
output$stab_xcol_det <- renderText({
xvar.det <- stab.variable.tbl()[variable %in% input$stab_xcol, .(detail)]
unique(xvar.det$detail)
})
output$ui_stab_xcat <- renderUI({
ifelse(input$stab_dataset == '2017/2019', d <- c('2017', '2019'), d <- '2021')
v <- variables.lu[survey_year %in% d, ]
cat <- unique(v$category)
selectInput('stab_xcat',
'Category',
cat)