-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththesis_stats_vis.R
1987 lines (1655 loc) · 78.4 KB
/
thesis_stats_vis.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
#### Sampo Vesanen's Master's thesis statistical tests and visualisation #######
# "Parking of private cars and spatial accessibility in Helsinki Capital Region"
# by Sampo Vesanen
# 15.10.2020
#
# This is an interactive tool for analysing the results of my research survey.
# Reference material for the tests
#https://stats.stackexchange.com/a/124618/262051
#https://rcompanion.org/handbook/E_01.html
#https://www.st-andrews.ac.uk/media/capod/students/mathssupport/OrdinalexampleR.pdf
#https://www.r-bloggers.com/box-plot-with-r-tutorial/
# Descriptive statistics
#https://www.fsd.uta.fi/menetelmaopetus/varianssi/harjoitus1.html
#http://www.sthda.com/english/wiki/one-way-anova-test-in-r
#https://datascienceplus.com/oneway-anova-explanation-and-example-in-r-part-1/
#http://www.sthda.com/english/wiki/compare-multiple-sample-variances-in-r
# About One-way ANOVA, Levene and BF
#https://en.wikipedia.org/wiki/One-way_analysis_of_variance
#https://www.statisticshowto.datasciencecentral.com/brown-forsythe-test/
#https://www.statisticshowto.datasciencecentral.com/levene-test/
#https://www.statisticshowto.datasciencecentral.com/homoscedasticity/
#https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5965542/ #levene+bf
#https://statistics.laerd.com/spss-tutorials/one-way-anova-using-spss-statistics-2.php
#### 1 Initialise --------------------------------------------------------------
rm(list = ls())
gc()
# App versions
app_a <- "15.10.2020"
app_v <- "13.10.2020"
#install.packages("onewaytests")
#install.packages("car")
#install.packages("plotrix")
#install.packages("moments")
#install.packages("shiny")
#install.packages("shinythemes")
#install.packages("ggplot2")
#install.packages("tidyr")
#install.packages("Rmisc")
#install.packages("dplyr")
#install.packages("dygraphs")
#install.packages("xts")
#install.packages("rgdal")
#install.packages("RColorBrewer")
#install.packages("shinyjs")
#install.packages("ggiraph")
#install.packages("widgetframe")
#install.packages("rgeos")
#install.packages("classInt")
#install.packages("rlang")
#install.packages("shinyWidgets")
#install.packages("grid")
#install.packages("ggsn")
# Libraries
library(onewaytests)
library(car)
library(plotrix)
library(moments)
library(shiny)
library(shinythemes)
library(ggplot2)
library(tidyr)
library(Rmisc)
library(dplyr)
library(dygraphs)
library(xts)
library(htmltools)
library(rgdal)
library(RColorBrewer)
library(shinyjs)
library(ggiraph)
library(widgetframe)
library(rgeos)
library(shinyWidgets)
library(grid)
library(ggsn)
# Working directory
wd <- "C:/Sampon/Maantiede/Master of the Universe/python"
# Python prepared data directories
datapath <- file.path(wd, "thesis_data_r/records_for_r.csv")
visitorpath <- file.path(wd, "thesis_data_r/visitors_for_r.csv")
postal_path <- file.path(wd, "thesis_data_r/postal_for_r.csv")
# Spatial data paths
suuraluepath <- file.path(wd, "thesis_data_r/PKS_suuralue.kml")
munspath <- file.path(wd, "thesis_data_r/hcr_muns_sea.shp")
othermunspath <- file.path(wd, "thesis_data_r/other_muns.shp")
unreachablepath <- file.path(wd, "thesis_data_r/hcr_muns_unreachable.shp")
# CSS data
csspath <- file.path(wd, "thesis_stats_vis_style.css")
jspath <- file.path(wd, "thesis_stats_vis_script.js")
# Source functions and postal code variables
source(file.path(wd, "thesis_stats_vis_funcs.R"))
#### 2 Preparation -------------------------------------------------------------
# These variables are used to subset dataframe thesisdata inside ShinyApp
continuous <- c("parktime", "walktime")
ordinal <- c("likert", "parkspot", "timeofday", "artificial", "ykr_zone",
"subdiv")
supportcols <- c("id", "timestamp", "ip")
int_cols <- c("n", "Min", "Max", "NA")
# Read in csv data. Define column types. Name factor levels. Determine order of
# factor levels for plotting. Lastly, remove column "X"
thesisdata <-
read.csv(file = datapath,
header = TRUE,
sep = ",",
colClasses = c(timestamp = "POSIXct", zipcode = "character",
ip = "character", timeofday = "factor",
parkspot = "factor", likert = "factor",
artificial = "factor", ykr_zone = "factor",
subdiv = "factor"),
stringsAsFactors = TRUE) %>%
dplyr::mutate(parkspot = dplyr::recode(
parkspot,
`1` = "On the side of street",
`2` = "Parking lot",
`3` = "Parking garage",
`4` = "Private or reserved",
`5` = "Other"),
likert = dplyr::recode(
likert,
`1` = "Extremely familiar",
`2` = "Moderately familiar",
`3` = "Somewhat familiar",
`4` = "Slightly familiar",
`5` = "Not at all familiar"),
timeofday = dplyr::recode(
timeofday,
`1` = "Weekday, rush hour",
`2` = "Weekday, other than rush hour",
`3` = "Weekend",
`4` = "Can't specify, no usual time"),
artificial = forcats::fct_relevel(
artificial,
c("Fully built",
"Predominantly built",
"Moderately built",
"Some built",
"Scarcely built")),
# SYKE does not provide official translations for
# "Yhdyskuntarakenteen vyohykkeet".
ykr_zone = forcats::fct_relevel(
ykr_zone,
c("keskustan jalankulkuvyöhyke",
"keskustan reunavyöhyke",
"alakeskuksen jalankulkuvyöhyke",
"intensiivinen joukkoliikennevyöhyke",
"joukkoliikennevyöhyke",
"autovyöhyke",
"novalue"))) %>%
dplyr::select(-X)
#### 3 Prepare layers ----------------------------------------------------------
#### 3.1 Subdivisions ----------------------------------------------------------
# Prepare a context map for to visualise currently active areas in analysis
# ShinyApp. left_join() preserves suuralue dataframe data. See ?"%>%" and "Using
# the dot for secondary purposes" for more information about the curly brackets.
# In short, it allows the use of dot as self for both fortify() and
# as.data.frame(). Then align area names with thesisdata$subdiv with mutate().
# Remove unnecessary column "Description" to save memory. Finally, factor levels
# by their new names.
app_crs <- sp::CRS("+init=epsg:3067")
suuralue_f <-
rgdal::readOGR(suuraluepath,
use_iconv = TRUE,
encoding = "UTF-8",
stringsAsFactors = TRUE) %>%
sp::spTransform(., app_crs) %>%
{dplyr::left_join(ggplot2::fortify(.),
as.data.frame(.) %>%
dplyr::mutate(id = as.character(dplyr::row_number() - 1)))} %>%
dplyr::select(-Description) %>%
dplyr::mutate(Name = factor(Name, labels =
c("Vantaa Aviapolis", "Helsinki Southern",
"Vantaa Hakunila", "Helsinki Eastern",
"Helsinki Southeastern", "Kauniainen",
"Helsinki Central", "Vantaa Kivistö",
"Helsinki Northeastern", "Vantaa Koivukylä",
"Vantaa Korso", "Helsinki Western",
"Vantaa Myyrmäki", "Helsinki Northern",
"Espoo Pohjois-Espoo", "Espoo Suur-Espoonlahti",
"Espoo Suur-Kauklahti", "Espoo Suur-Leppävaara",
"Espoo Suur-Matinkylä", "Espoo Suur-Tapiola",
"Vantaa Tikkurila", "Espoo Vanha-Espoo",
"Helsinki Östersundom"))) %>%
dplyr::mutate(Name = factor(Name, levels = sort(levels(Name))))
suuralue_f <- suuralue_f[order(suuralue_f$Name), ]
#### 3.2 Municipality borders --------------------------------------------------
# Get municipality borders from shapefile.
# Shapefile data is Regional population density 2012, Statistics Finland.
# http://urn.fi/urn:nbn:fi:csc-kata00001000000000000226.
muns_f <-
rgdal::readOGR(munspath, stringsAsFactors = TRUE) %>%
sp::spTransform(., app_crs) %>%
{dplyr::left_join(ggplot2::fortify(.),
as.data.frame(.) %>%
dplyr::mutate(id = as.character(dplyr::row_number() - 1)))}
# Islands in Helsinki Capital Region that are unreachable by car in PAAVO dataset
unreachable_f <-
rgdal::readOGR(unreachablepath, stringsAsFactors = TRUE) %>%
sp::spTransform(., app_crs) %>%
ggplot2::fortify(.)
# Bordering municipalities. Does not require any of the shapefile attribute data.
othermuns_f <-
rgdal::readOGR(othermunspath, stringsAsFactors = TRUE) %>%
sp::spTransform(., app_crs) %>%
ggplot2::fortify(.)
#### 3.3 Annotation ------------------------------------------------------------
# Annotate municipalities and subdivisions for ggplot2
muns_cntr <- GetCentroids(muns_f, "nimi", "nimi")
subdiv_cntr <- GetCentroids(suuralue_f, "Name", "Name")
# Manually set better location for the annotation of Helsinki and Espoo. Utilise
# custom infix operators.
muns_cntr["Helsinki", "lat"] %+=% 2000
muns_cntr["Espoo", "lat"] %+=% 1100
muns_cntr$label <- c("Espoo", "Helsinki", "Kauniainen", "Vantaa")
# Name labels here so that all the reordering doesn't mix stuff up. Remove
# munnames from subdiv annotations
subdiv_cntr$label <- gsub(".* ", "", unique(suuralue_f$Name))
rownames(subdiv_cntr) <- gsub(".* ", "", unique(suuralue_f$Name))
# Manually move labels for Espoonlahti and Southeastern as we are going to use
# some y axis limits when drawing the map. For Espoonlahti, take lat of Helsinki
# Southern. For long, take Pohjois-Espoo's. For Southeastern, take long of Korso.
subdiv_cntr["Suur-Espoonlahti", "lat"] <- subdiv_cntr["Southern", "lat"]
subdiv_cntr["Suur-Espoonlahti", "long"] <- subdiv_cntr["Pohjois-Espoo", "long"]
subdiv_cntr["Southeastern", "lat"] <- subdiv_cntr["Southern", "lat"] + 1500
subdiv_cntr["Southeastern", "long"] <- subdiv_cntr["Korso", "long"]
subdiv_cntr["Southern", "lat"] %+=% 3000
subdiv_cntr["Östersundom", "lat"] %-=% 500
subdiv_cntr["Östersundom", "long"] %-=% 400
subdiv_cntr["Suur-Matinkylä", "lat"] %-=% 500
### 4 Interactive map for ShinyApp ---------------------------------------------
# Created with the help of:
# https://bhaskarvk.github.io/user2017.geodataviz/notebooks/03-Interactive-Maps.nb.html
zips <- unique(thesisdata$zipcode)
# Get postal code area data calculated in Python. It contains some interesting
# variables for visualisation. Select essential columns and multiply column
# "artificial" with 100 for easier to view plotting
postal <-
read.csv(file = postal_path,
header = TRUE,
sep = ",",
colClasses = c(zipcode = "factor", kunta = "factor"),
stringsAsFactors = TRUE) %>%
dplyr::select(c(2, 3, 6, 108:121)) %>%
dplyr::mutate(artificial = artificial * 100)
# Create the column in "postal" which reports the largest ykr zone in each postal
# code area
largest_ykr <- colnames(postal[, 5:11])[apply(postal[, 5:11], 1, which.max)]
largest_ykr <- gsub("ykr_", "", largest_ykr)
largest_ykr_no <- as.numeric(apply(postal[, 5:11], 1, max)) * 100
postal <- cbind(postal, largest_ykr = paste(largest_ykr, largest_ykr_no))
# "postal" geometries are in well-known text format. Some processing is needed
# to utilise these polygons in R. readWKT()
geometries <- lapply(postal[, "geometry"], "readWKT", p4s = app_crs)
sp_tmp_ID <- mapply(sp::spChFIDs, geometries, as.character(postal[, 1]))
row.names(postal) <- postal[, 1]
data_f <- sp::SpatialPolygonsDataFrame(
sp::SpatialPolygons(unlist(lapply(sp_tmp_ID, function(x) x@polygons)),
proj4string = app_crs), data = postal) %>%
# Fortify and preserve Polygon attribute data
{dplyr::left_join(ggplot2::fortify(.),
as.data.frame(.) %>%
dplyr::mutate(id = as.character(zipcode)),
by = "id")}
#### 5 Analysis ShinyApp -------------------------------------------------------
# This ShinyApp is a versatile tool to study the thesis survey data. One can
# choose parameters with lots of freedom and exclude options as seen fit.
server <- function(input, output, session){
#### 5.1 Listener functions --------------------------------------------------
# 5.1.1 Listen to clear subdivs button ---------------------------------------
observeEvent(input$resetSubdivs, {
shinyjs::reset("subdivGroup")
})
observeEvent(input$resetParkWalk, {
shinyjs::reset("parktime_max")
shinyjs::reset("walktime_max")
})
#### 5.1.2 Reactive data -----------------------------------------------------
# currentdata(), currentpostal() and current_data_f() are reactive objects
# made to keep track of changes the Shiny application. Most of the app uses
# only currentdata(), but the interactive map utilises all of them.
# Detect user setting for maximum parktime and walktime.
# currentdata() is the currently active rows of the original thesisdata
# DataFrame. Use currentdata() in the rest of the application to not interfere
# with the original dataset.
currentdata <- shiny::reactive(
# Use ! negation to remove checkGroup and subdivGroup inputs from
# thesisdata.
dplyr::filter(thesisdata,
!(!!rlang::sym(input$expl)) %in% input$checkGroup,
!subdiv %in% input$subdivGroup,
parktime <= input$parktime_max,
walktime <= input$walktime_max)
)
# currentpostal() recalculates, when needed, new answer counts, means, and
# medians for the values currently active in currentdata(). This is needed to
# make the interactive map tooltip values responsive to changes. In this phase,
# we calculate the required data, the actual mapping part is in current_data_f()
currentpostal <- shiny::reactive({
currentdata <- currentdata()
# tidyr::complete() helps find missing zipcodes and give them n=0
result <- postal %>%
dplyr::mutate(answer_count = currentdata %>%
dplyr::group_by(zipcode) %>%
dplyr::tally() %>%
tidyr::complete(zipcode = zips, fill = list(n = NA)) %>%
dplyr::pull(n),
parktime_mean = currentdata %>%
dplyr::group_by(zipcode) %>%
dplyr::summarise(mean(parktime)) %>%
tidyr::complete(zipcode = zips, fill = list(n = NA)) %>%
dplyr::pull(),
parktime_median = currentdata %>%
dplyr::group_by(zipcode) %>%
dplyr::summarise(median(parktime)) %>%
tidyr::complete(zipcode = zips, fill = list(n = NA)) %>%
dplyr::pull(),
walktime_mean = currentdata %>%
dplyr::group_by(zipcode) %>%
dplyr::summarise(mean(walktime)) %>%
tidyr::complete(zipcode = zips, fill = list(n = NA)) %>%
dplyr::pull(),
walktime_median = currentdata %>%
dplyr::group_by(zipcode) %>%
dplyr::summarise(median(walktime)) %>%
tidyr::complete(zipcode = zips, fill = list(n = NA)) %>%
dplyr::pull(),
# this enables turning off subdivs and the result being
# visible on interactive map
artificial = currentdata %>%
dplyr::group_by(zipcode) %>%
dplyr::summarise(mean(artificial_vals)) %>%
tidyr::complete(zipcode = zips, fill = list(n = NA)) %>%
dplyr::pull()) %>%
dplyr::mutate(artificial = artificial * 100)
result$parktime_mean <- sapply(result[, "parktime_mean"], round, 2)
result$walktime_mean <- sapply(result[, "walktime_mean"], round, 2)
result
})
# current_data_f() produces the currently needed interactive map out of the
# data contained in currentpostal(). This is a copy of the code above, seen
# in "Interactive map for ShinyApp". Please See code comments in the original.
current_data_f <- shiny::reactive({
currentpostal <- currentpostal()
geometries <- lapply(currentpostal[, "geometry"], "readWKT", p4s = app_crs)
sp_tmp_ID <- mapply(sp::spChFIDs, geometries, as.character(currentpostal[, 1]))
row.names(currentpostal) <- currentpostal[, 1]
data_f <- sp::SpatialPolygonsDataFrame(
sp::SpatialPolygons(unlist(lapply(sp_tmp_ID, function(x) x@polygons)),
proj4string = app_crs), data = currentpostal) %>%
{dplyr::left_join(ggplot2::fortify(.),
as.data.frame(.) %>%
dplyr::mutate(id = as.character(zipcode)),
by = "id")}
data_f
})
shiny::observe({
# 5.1.3 Detect changes in selectInput to modify available check boxes ------
x <- input$expl
updateCheckboxGroupInput(
session,
"checkGroup",
label = NULL,
choiceNames = levels(thesisdata[, x]),
choiceValues = levels(thesisdata[, x]), )
# 5.1.4 Determine availability of barplot ----------------------------------
# aka availability of "Distribution of ordinal variables"
available <- c("likert", "parkspot", "timeofday", "artificial", "ykr_zone",
"subdiv")
updateSelectInput(
session,
"barplot",
label = NULL,
choices = available[!available == x])
# 5.1.5 Do not allow selection of all checkboxes in Jenks ------------------
if(length(input$kunta) == 3) {
threevalues <<- input$kunta
}
if(length(input$kunta) > 3) {
updateCheckboxGroupInput(
session,
"kunta",
selected = threevalues)
}
# 5.1.6 A clumsy implementation to listen for too large Jenks breaks -------
inputpostal <- postal[!postal$kunta %in% c(input$kunta), ]
if(input$karttacol == "jenks_artificial") {
datacol <- "artificial"
} else if (input$karttacol == "jenks_walk_median") {
datacol <- "walktime_median"
} else if (input$karttacol == "jenks_park_median") {
datacol <- "parktime_median"
} else if (input$karttacol == "jenks_answer_count") {
datacol <- "answer_count"
} else if (input$karttacol == "jenks_walk_mean") {
datacol <- "walktime_mean"
} else if (input$karttacol == "jenks_park_mean") {
datacol <- "parktime_mean"
}
# Only test classIntervals() and change SliderInput value if statement holds.
# Suppress warnings in the test.
if(nrow(inputpostal) > 1) {
classes_test <- suppressWarnings(
classInt::classIntervals(inputpostal[, datacol], n = input$jenks_n,
style = "jenks"))
# Object returned from classIntervals() has an attribute nobs which I
# use to detect cases where too large input$jenks_n is inputted to
# CreateJenksColumn() function
if(attributes(classes_test)$nobs < input$jenks_n) {
updateSliderInput(session,
"jenks_n",
value = attributes(classes_test)$nobs)
}
}
})
#### 5.2 Descriptive statistics ----------------------------------------------
output$descri <- renderTable({
# Vital variables
resp_col <- input$resp
expl_col <- input$expl
thisFormula <- as.formula(paste(resp_col, '~', expl_col))
# In each output, define reactive variable as "inpudata". According to
# this Stack Overflow answer, it prevents errors down the line
# https://stackoverflow.com/a/53989498/9455395
# Reminder: the reactive currentdata() is called to keep track of maximum
# allowed parktime and walktime values, and see changes in input$checkGroup
# and input$subdivGroup
inputdata <- currentdata()
# Take subdiv checkbox group into account
inputdata <- inputdata[, !names(inputdata) %in% supportcols]
response <- inputdata[[resp_col]]
# Basic descriptive statistics
desc <- onewaytests::describe(thisFormula, inputdata)
### Mean and standard error
# Clumsily calculate mean, so that we can preserve column names in the next
# phase. Adapt code from: https://stackoverflow.com/a/41029914/9455395
stder <- aggregate(
thisFormula,
data = inputdata,
FUN = function(x) c(mean = mean(x), "Std.Error" = plotrix::std.error(x)))
# Remove column "mean"
stder <- subset(stder[[2]], select = -mean)
desc <- cbind(desc, stder)
# Confidence intervals for mean
confs <- aggregate(
thisFormula,
data = inputdata,
FUN = function(x) c("CI for mean, lower bound" = Rmisc::CI(x)[[3]],
"CI for mean, upper bound" = Rmisc::CI(x)[[1]]))
confs <- confs[[2]]
desc <- cbind(desc, confs)
# Reorder to SPSS descriptive statistics order
desc <- desc[c("n", "Median", "Mean", "Std.Dev", "Std.Error",
"CI for mean, lower bound", "CI for mean, upper bound", "Min",
"Max", "25th", "75th", "Skewness", "Kurtosis", "NA")]
# Add the total row. We will add total values for all columns in this manner,
# using "response" which is all currently active parktime or walktime values.
vect <- c()
vect[1] <- length(response)
vect[2] <- median(response)
vect[3] <- mean(response)
vect[4] <- sd(response)
vect[5] <- plotrix::std.error(response)
vect[6] <- Rmisc::CI(response)[[3]]
vect[7] <- Rmisc::CI(response)[[1]]
vect[8] <- min(response)
vect[9] <- max(response)
vect[10] <- quantile(response)[2]
vect[11] <- quantile(response)[4]
vect[12] <- moments::skewness(response)
vect[13] <- moments::kurtosis(response)
vect[14] <- sum(is.na(response))
# Add "vect" to "desc" as a new row, then name the new row. Finally, set
# specific columns as integer to prevent useless decimal places in
# tableOutput
desc <- rbind(desc, vect)
row.names(desc)[nrow(desc)] <- "Total" # name the last row
desc[int_cols] <- sapply(desc[int_cols], as.integer)
desc_out <<- desc # Result to global environment to enable download
# Render descriptive statistics table
desc
},
striped = TRUE,
hover = TRUE,
bordered = TRUE,
rownames = TRUE,
digits = 2)
#### 5.2.1 Download descriptive statistics ----
output$dl_descri <- downloadHandler(
filename = function() {
paste("descriptives_",
"pmax", input$parktime_max, "-wmax", input$walktime_max, "_",
input$resp, "-", input$expl, "_",
format(Sys.time(), "%d-%m-%Y"),
".csv",
sep = "")
},
content = function(file) {
write.csv(desc_out, file)
}
)
#### 5.3 Histogram for parktime or walktime ----------------------------------
output$hist <- renderggiraph({
resp_col <- input$resp
expl_col <- input$expl
binwidth <- input$bin
inputdata <- currentdata()
resp_vect <- inputdata[[resp_col]] # for vertical line labels
# These textGrobs determine the value shown at the bottom of vertical mean and
# median geom_vlines. Produce objects separately for the normal version and
# the downloadable versions to control font size.
meanval <- round(mean(resp_vect), 2)
medianval <- round(median(resp_vect), 2)
meangrob <- grid::textGrob(label = meanval,
hjust = -0.3,
vjust = 1.25,
gp = grid::gpar(cex = 1.2, col = "red"))
mediangrob <- grid::textGrob(label = medianval,
hjust = 2,
vjust = 1.25,
gp = grid::gpar(cex = 1.2, col = "blue"))
meangrob_out <- grid::textGrob(label = meanval,
hjust = -0.3,
vjust = 1.25,
gp = grid::gpar(cex = 2.2, col = "red"))
mediangrob_out <- grid::textGrob(label = medianval,
hjust = 2,
vjust = 1.25,
gp = grid::gpar(cex = 2.2, col = "blue"))
p <- ggplot(inputdata, aes(x = !!sym(resp_col))) +
geom_histogram(color = "black", fill = "grey", binwidth = binwidth) +
xlab(paste(resp_col, "(min)")) +
# Vertical lines for mean and median, respectively. Also display exact
# values with annotate_custom() and textGrobs. They are added a bit later.
geom_vline(aes(xintercept = mean(!!sym(resp_col)),
color = "mean"),
linetype = "longdash",
size = 1) +
geom_vline(aes(xintercept = median(!!sym(resp_col)),
color = "median"),
linetype = "longdash",
size = 1) +
# This is kernel density estimate, a smoothed version of the histogram.
# Usually geom_density() sets the scale for y axis, but here we will
# continue using count/frequency. This requires some work on our behalf.
# Idea from here: https://stackoverflow.com/a/27612438/9455395
geom_density(aes(y = ..density.. * (nrow(inputdata) * binwidth),
color = "kernel density\nestimate"),
show.legend = FALSE,
adjust = binwidth) +
# increase amount of ticks on x axis
scale_x_continuous(breaks = seq(0, max(resp_vect), by = 10)) +
theme(legend.key.size = unit(1.5, "line"),
legend.title = element_text(size = 16),
legend.text = element_text(size = 15),
legend.spacing.y = unit(0.4, "cm"),
legend.position = c(0.92, 0.79),
axis.text = element_text(size = 13),
axis.title = element_text(size = 15),
text = element_text(size = 13)) +
guides(shape = guide_legend(override.aes = list(size = 1.5)),
color = guide_legend(override.aes = list(size = 1.5))) +
# Build legend, override colors to get a visible color for density. Also,
# override linetype to get a solid line for density.
scale_color_manual(name = paste("Legend for\n", resp_col, sep = ""),
values = c(median = "blue",
mean = "red",
"kernel density\nestimate" = alpha("black", 0.4))) +
guides(color = guide_legend(
override.aes = list(color = c("darkgrey", "red", "blue"),
linetype = c("solid", "longdash", "longdash"))))
# Conditional histogram bar labeling. No label for zero. Create the labeling
# separately for the histogram shown in the app and the histogram made for
# downloading. To my knowledge there is no other way to control the font size.
# Also add annotations for geom_vlines here.
p_out <- p + stat_bin(binwidth = binwidth,
geom = "text",
aes(label = ifelse(..count.. > 0, ..count.., "")),
vjust = -0.65) +
annotation_custom(
grob = meangrob,
ymin = 0,
ymax = 0,
xmin = meanval,
xmax = meanval) +
annotation_custom(
grob = mediangrob,
ymin = 0,
ymax = 0,
xmin = medianval,
xmax = medianval)
# Prepare the downloadable histogram. "hist_out" is brought global environment
# for download. Use larger fonts.
hist_out <- LabelBuilder(p, input$expl, input$checkGroup, input$subdivGroup)
hist_out <-
hist_out +
# a larger font size for bar labeling
stat_bin(binwidth = binwidth,
geom = "text",
aes(label = ifelse(..count.. > 0, ..count.., "")),
size = 9.5,
vjust = -0.65) +
# Larger fonts for geom_vline annotations
annotation_custom(
grob = meangrob_out,
ymin = 0,
ymax = 0,
xmin = meanval,
xmax = meanval) +
annotation_custom(
grob = mediangrob_out,
ymin = 0,
ymax = 0,
xmin = medianval,
xmax = medianval) +
theme(legend.key.size = unit(1.5, "line"),
legend.title = element_text(size = 32),
legend.text = element_text(size = 30),
legend.spacing.y = unit(0.6, "cm"),
legend.position = c(0.92, 0.78),
axis.text = element_text(size = 26),
axis.title = element_text(size = 29),
legend.key = element_rect(size = 6),
legend.key.height = unit(1.5, "cm"),
legend.key.width = unit(1, "cm")) +
# this enables larger legend symbols. To my knowledge, I have to redefine
# the whole aes() here
guides(color = guide_legend(
override.aes = list(color = c("grey60", "red", "blue"),
linetype = c("solid", "longdash", "longdash"),
size = 2.5)))
# This is a crude way of updating plot values. Depends on knowing the
# indices of plot items. Unpack plot with ggplot_build(), then reassemble
# with ggplot_gtable().
disassembled <- ggplot_build(hist_out)
disassembled$data[[1]]$size <- 1 # bars
disassembled$data[[2]]$size <- 1.5 #mean
disassembled$data[[3]]$size <- 1.5 #median
disassembled$data[[4]]$size <- 1.5 #density
hist_out <<- ggplot_gtable(disassembled)
# Render histogram
ggiraph(code = print(p_out),
width_svg = 17,
height_svg = 6)
})
#### 5.3.1 Download histogram ----
output$dl_hist <- downloadHandler(
filename = function() {
paste("hist_",
"pmax", input$parktime_max, "-wmax", input$walktime_max, "_",
input$resp, "-", input$expl, "_",
"binw", input$bin, "_",
format(Sys.time(), "%d-%m-%Y"),
".png",
sep = "")
},
content = function(file) {
ggsave(plot = hist_out, file, height = 10, width = 26, dpi = 150)
}
)
#### 5.4 Barplot -------------------------------------------------------------
output$barplot_ord <- renderggiraph({
# See distribution of ordinal variables through a grouped bar plot
expl_col <- input$expl
barplotval <- input$barplot
yax <- paste("count of", barplotval)
# Listen to user choices
inputdata <- currentdata()
# Plot maximum y tick value. Use dplyr to group the desired max amount.
# In dplyr, use !!as.symbol(var) to signify that we are using variables
# as column names
maximum <- inputdata %>%
dplyr::group_by(!!as.symbol(expl_col), !!as.symbol(barplotval)) %>%
dplyr::summarise(amount = length(!!as.symbol(barplotval))) %>%
dplyr::top_n(n = 1) %>%
dplyr::pull(amount) %>%
max()
if (maximum <= 200) {
tick_interval <- 50
} else {
tick_interval <- 200
}
tooltip_content <- paste0("<div id='app-tooltip'>",
"<div>n=%s</div>",
"</div>")
plo <-
ggplot(inputdata, aes(x = get(expl_col),
y = factor(get(barplotval)),
fill = get(barplotval))) +
# Setting width and position_dodge adds space between bars. Add a simple
# tooltip.
geom_bar_interactive(aes(y = stat(count),
tooltip = sprintf(tooltip_content,
..count..)),
width = 0.8,
position = position_dodge(width = 0.9)) +
scale_y_continuous(breaks = seq(0, maximum, by = tick_interval),
expand = expansion(mult = c(0, .1))) +
xlab(expl_col) +
ylab(yax) +
labs(fill = barplotval) +
theme(legend.position = "bottom",
legend.title = element_text(size = 16),
legend.text = element_text(size = 15),
axis.text = element_text(size = 13),
axis.title = element_text(size = 15))
# Use RColorBrewer color scale. Paired has 12 set colors, interpolate if
# there are more values to map than that.
legendnames <- unique(inputdata[[barplotval]])
plo <- InterpolateGgplotColors(plo, legendnames, 12, "Paired")
# Prepare the downloadable barplot. "barplot_out" is brought global
# environment for download. Use larger fonts.
# Labeling inactive checkGroup values is not meaningful in the barplot
barplot_out <- LabelBuilder(plo, "", c(), input$subdivGroup)
barplot_out <<-
barplot_out +
theme(legend.title = element_text(size = 22),
legend.text = element_text(size = 21),
axis.text = element_text(size = 20),
axis.title = element_text(size = 22))
# Render barplot
ggiraph(code = print(plo),
width_svg = 16.7,
height_svg = 6)
})
#### 5.4.1 Download barplot ----
output$dl_barplot <- downloadHandler(
filename = function() {
paste("barplot_",
"pmax", input$parktime_max, "-wmax", input$walktime_max, "_",
input$expl, "-", input$barplot, "_",
format(Sys.time(), "%d-%m-%Y"),
".png",
sep = "")
},
content = function(file) {
ggsave(plot = barplot_out, file, height = 10, width = 26, dpi = 150)
}
)
#### 5.5 Boxplot -------------------------------------------------------------
output$boxplot <- renderggiraph({
expl_col <- input$expl
resp_col <- input$resp
thisFormula <- as.formula(paste(resp_col, '~', expl_col))
# Listen to user choices
inputdata <- currentdata()
legendnames <- levels(unique(inputdata[[expl_col]]))
inputdata <- CalcBoxplotTooltip(inputdata, resp_col, expl_col)
tooltip_content <- paste0("<div id='app-tooltip'>",
"<div>Max = %s</div>",
"<hr id='tooltip-hr'>",
"<b>Interquartile<br/>Range (IQR)</b><br/>",
"<div id='tooltip-div'>Q3 = %s<br/>",
"Med = %s<br/>",
"Q1 = %s</div>",
"<hr id='tooltip-hr'>",
"<div id='tooltip-div'>Min = %s</div>",
"</div")
# ggplot2 plotting. Rotate labels if enough classes. Use scale_fill_hue()
# to distinguish boxplot colors from barplot colors.
p <- ggplot(inputdata, aes_string(x = expl_col,
y = resp_col,
fill = expl_col)) +
geom_boxplot_interactive(aes(tooltip = sprintf(tooltip_content,
tooltip_max,
tooltip_q3,
tooltip_mdn,
tooltip_q1,
tooltip_min))) +
ylab(paste(resp_col, "(min)")) +
theme(axis.text = element_text(size = 13),
axis.title = element_text(size = 15),
legend.position = "none")
# Use RColorBrewer color scale. Set3 has 12 set colors, interpolate if
# there are more values to map than that.
p <- InterpolateGgplotColors(p, legendnames, 12, "Set3")
# Diagonal labels if more values to map than five
if(length(legendnames) > 5) {
p <- p + theme(axis.text.x = element_text(size = 13, angle = 45, hjust = 1))
}
# Prepare the downloadable boxplot. "boxplot_out" is brought global environment
# for download. Use larger fonts.
# Labeling inactive checkGroup values is not meaningful in the boxplot
boxplot_out <- LabelBuilder(p, "", c(), input$subdivGroup)
boxplot_out <<-
boxplot_out +
theme(axis.text = element_text(size = 21),
axis.title = element_text(size = 23),
axis.text.x = element_text(size = 21))
# Render boxplot
ggiraph(code = print(p),
width_svg = 16.7,
height_svg = 7)
})
#### 5.5.1 Download boxplot ----
output$dl_boxplot <- downloadHandler(
filename = function() {
paste("boxplot_",
"pmax", input$parktime_max, "-wmax", input$walktime_max, "_",
input$resp, "-", input$expl, "_",
format(Sys.time(), "%d-%m-%Y"),
".png",
sep = "")
},
content = function(file) {
ggsave(plot = boxplot_out, file, height = 12, width = 26, dpi = 150)
}
)
#### 5.6 Levene test ---------------------------------------------------------
output$levene <- renderTable({
expl_col <- input$expl
thisFormula <- as.formula(paste(input$resp, "~", expl_col))
inputdata <- currentdata()
levene <- car::leveneTest(thisFormula, inputdata, center = mean)