-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.R
2473 lines (2273 loc) · 124 KB
/
app.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
library(shiny)
library(dplyr)
library(tidyr)
library(ggplot2)
library(stats)
library(shinydashboard)
library(shinythemes)
library(metathis)
library(stringr)
library(shinyjs)
library(shinyWidgets)
library(r2d3)
library(radarchart)
library(haven)
library(highcharter)
library(rgeos)
library(scales)
library(grDevices)
library(shinyalert)
library(shinyBS)
library(htmltools)
library(purrr)
library(RColorBrewer)
library(lubridate)
source("R/dependencies.R")
source("R/input-multi.R")
source("R/utils.R")
#source("data_prep_shiny_labels.R")
# R Studio Clean-Up:
#cat("\014") # clear console
#rm(list=ls()) # clear workspace (better way: Ctrl+Shift+F10 but make sure that you are not saving your workspace to your .Rdata file)
#gc() # garbage collector
#setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) # usually set by project
# load data:
# data creation not possible in docker container (i.e., on server)
# if (!file.exists("data/shinyDataAggregated.RData")) {
# data_prep()
# }
load("data/shinyDataAggregated.RData")
load("data/shinyDataLongitudinal.RData")
updateMultiInput_2 <- function (session, inputId, label = NULL, selected = NULL, choices = NULL, choiceValues = NULL, choiceNames = NULL) {
if (is.null(choices)) {
if (is.null(choiceValues))
stop("If choices = NULL, choiceValues must be not NULL")
if (length(choiceNames) != length(choiceValues)) {
stop("`choiceNames` and `choiceValues` must have the same length.")
}
choiceValues <- as.list(choiceValues)
choiceNames <- as.list(choiceNames)
choices_2 <- tagList(
lapply(
X = seq_along(choiceNames),
FUN = function(i) {
htmltools::tags$option(value = choiceValues[[i]], as.character(choiceNames[[i]]),
selected = if(choiceValues[[i]] %in% selected) "selected")
}
)
)
}
else {
choices_2 <- if (!is.null(choices))
choicesWithNames(choices_2)
}
if (!is.null(selected))
selected <- validateSelected(selected, choices_2, inputId)
options <- as.character(makeChoices(choices = choices, choiceValues = choiceValues, choiceNames = choiceNames, selected = selected))
message <- dropNulls(list(label = label, options = options, value = selected))
session$sendInputMessage(inputId, message)
}
r2d3_script <- "
// !preview r2d3 data= data.frame(y = 0.1, ylabel = '1%', fill = '#E69F00', mouseover = 'green', label = 'one', id = 1)
function svg_height() {return parseInt(svg.style('height'))}
function svg_width() {return parseInt(svg.style('width'))}
function col_top() {return svg_height() * 0.05; }
function col_left() {return svg_width() * 0.25;}
function actual_max() {return d3.max(data, function (d) {return d.y; }); }
function col_width() {return (svg_width() / actual_max()) * 0.60; }
function col_heigth() {return svg_height() / data.length * 0.95; }
var bars = svg.selectAll('rect').data(data);
bars.enter().append('rect')
.attr('x', 170)
.attr('y', function(d, i) { return i * col_heigth() + col_top(); })
.attr('width', function(d) { return d.y * col_width(); })
.attr('height', col_heigth() * 0.9)
.attr('fill', function(d) {return d.fill; })
.attr('id', function(d) {return (d.label); })
.on('click', function(){
Shiny.setInputValue('bar_clicked', d3.select(this).attr('id'), {priority: 'event'});
})
.on('mouseover', function(){
d3.select(this).attr('fill', function(d) {return d.mouseover; });
})
.on('mouseout', function(){
d3.select(this).attr('fill', function(d) {return d.fill; });
});
bars.transition()
.duration(500)
.attr('x', 170)
.attr('y', function(d, i) { return i * col_heigth() + col_top(); })
.attr('width', function(d) { return d.y * col_width(); })
.attr('height', col_heigth() * 0.9)
.attr('fill', function(d) {return d.fill; })
.attr('id', function(d) {return d.label; });
bars.exit().remove();
// Identity labels
var txt = svg.selectAll('text').data(data);
txt.enter().append('text')
.attr('x', width * 0.01)
.attr('y', function(d, i) { return i * col_heigth() + (col_heigth() / 2) + col_top(); })
.text(function(d) {return d.label; })
.style('font-family', 'sans-serif');
txt.transition()
.duration(1000)
.attr('x', width * 0.01)
.attr('y', function(d, i) { return i * col_heigth() + (col_heigth() / 2) + col_top(); })
.text(function(d) {return d.label; });
txt.exit().remove();
// Numeric labels
var totals = svg.selectAll().data(data);
totals.enter().append('text')
.attr('x', function(d) { return ((d.y * col_width()) + 170) * 1.01; })
.attr('y', function(d, i) { return i * col_heigth() + (col_heigth() / 2) + col_top(); })
.style('font-family', 'sans-serif')
.text(function(d) {return d.ylabel; });
totals.transition()
.duration(1000)
.attr('x', function(d) { return ((d.y * col_width()) + 170) * 1.01; })
.attr('y', function(d, i) { return i * col_heigth() + (col_heigth() / 2) + col_top(); })
.attr('d', function(d) { return d.x; })
.text(function(d) {return d.ylabel; });
totals.exit().remove();
"
r2d3_file <- tempfile()
writeLines(r2d3_script, r2d3_file)
all_valid_ctry <- ctry.scales$coded_country
all_valid_ctry.only.red <- all_valid_ctry[! all_valid_ctry %in% c("global")]
repr_valid_ctry <- ctry.scales.representative$coded_country
repr_valid_ctry.only.red <- repr_valid_ctry[! repr_valid_ctry %in% c("global")]
# TODO: TEMPORARY: ADD TO DATA_PREP()
ctry.red.repr <- ctry.scales.representative %>% dplyr::select(coded_country, iso_a2, flag, n)
ctry.only.red.repr <- ctry.red.repr[!ctry.red.repr$coded_country %in% c("global"),]
# TODO: temporary: make sure that the columns of ctry.scales and ctry.scales.representative are identical
ctry.scales <- ctry.scales[names(ctry.scales.representative)]
ctry.scales_s <- ctry.scales_s[names(ctry.scales.representative_s)]
# TODO: rename column names
names(ctry.scales_s) <- sub("_Standardized", "", names(ctry.scales_s))
names(ctry.scales.representative_s) <- sub("_Standardized", "", names(ctry.scales.representative_s))
z.min <- min(ctry.scales_s %>% dplyr::select_if(., is.numeric), na.rm = T)
z.max <- max(ctry.scales_s %>% dplyr::select_if(., is.numeric), na.rm = T)
# Default
select_ctry_sample <- all_valid_ctry
select_ctry_psych <- "global"
select_sample <- "full"
select_transformation <- "raw"
latest.DateTime <- file.info("app.R")$mtime
# -----
ui <- dashboardPage(
title = "PsyCorona: Data Visualization",
dashboardHeader(title=span( icon("fas fa-virus"), "PsyCorona Data Tool") #HTML(paste(icon("virus"), "PsyCorona Data Tool")),
# dropdownMenu(type = "notifications",
# notificationItem(text = "Data is currenlty not accurate",
# icon = icon("warning"),
# status = "warning")
# )
),
dashboardSidebar(
sidebarMenu(id = "sidebarMenu",
menuItem("The Sample", tabName = "sample", icon = icon("fas fa-users")),
menuItem("Psychological Variables", tabName = "Variables", icon = icon("fas fa-pencil-ruler")),
menuItem("Development", tabName = "development", icon = icon("fas fa-chart-line"), badgeLabel = "new", badgeColor = "blue"),
menuItem("Data", tabName = "data", icon = icon("fas fa-share-square")),
menuItem("About", tabName = "about", icon = icon("info")),
menuItem(HTML(paste0("Take the survey now ", icon("external-link"))), icon=icon("fas fa-file-signature"), href = "https://nyu.qualtrics.com/jfe/form/SV_6svo6J4NF7wE6tD", newtab = T),
uiOutput("dynamic_content")),
shinyjs::useShinyjs(),
tags$footer(HTML("<strong>Copyright © 2020 <a href=\"https://psycorona.org/about/\" target=\"_blank\">PsyCorona</a>.</strong>
<br>This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-nd/4.0/\" target=\"_blank\">Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License</a>.
<br><a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-nd/4.0/\" target=\"_blank\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-nd/4.0/88x31.png\" /></a>
<br>Last updated:<br>"),
latest.DateTime,
id = "sideFooter",
align = "left",
style = "
position:absolute;
bottom:0;
width:100%;
padding: 10px;
"
)
#HTML("<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-nd/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-nd/4.0/88x31.png\" /></a><br />This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-nd/4.0/\">Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License</a>.")
#)
),
dashboardBody(
tags$script(HTML("$('body').addClass('sidebar-mini');")),
tags$head(tags$link(rel = "stylesheet", type = "text/css", href = "style.css")),
tags$head(tags$meta(name = "viewport", content = "width=1600"), uiOutput("body")),
tags$head(tags$link(rel = "shortcut icon", href = "favicon.ico")),
#tags$head(tags$link(rel="shortcut icon", href="https://github.com/raw/JannisCodes/PsyCorona-WebApp/master/www/faviconData.png")),
tags$head(tags$link(rel = "shortcut icon", href = "favicon.ico")),
tags$style(
type = 'text/css',
'.bg-aqua {background-color: #3c8dbe!important; }
.bttn-simple.bttn-primary {background-color: #3c8dbe!important; }
.btn.radiobtn.btn-primary {float: center!important;
display: block;
width: 160px}
'
),
tags$style("@import url(https://use.fontawesome.com/releases/v5.13.0/css/all.css);"),
tags$script(src = "https://code.highcharts.com/mapdata/custom/world.js"),
tags$script(HTML("
var openTab = function(tabName){
$('a', $('.sidebar')).each(function() {
if(this.getAttribute('data-value') == tabName) {
this.click()
};
});
};
$('.sidebar-toggle').attr('id','menu');
var dimension = [0, 0];
$(document).on('shiny:connected', function(e) {
dimension[0] = window.innerWidth;
dimension[1] = window.innerHeight;
Shiny.onInputChange('dimension', dimension);
});
$(window).resize(function(e) {
dimension[0] = window.innerWidth;
dimension[1] = window.innerHeight;
Shiny.onInputChange('dimension', dimension);
});
")),
meta() %>%
meta_social(
title = "PsyCorona: Data Visualization",
description = paste0("A tool to explore the patterns of psychological reactions to the Covid-19 epidemic across ", nrow(ctry.only.red), " countries."),
url = "https://psycorona.shinyapps.io/WebApp/",
image = "https://github.com/raw/JannisCodes/PsyCorona-WebApp/master/www/media.png",
image_alt = "PsyCorona Data Tool",
twitter_creator = "@JannisWrites",
twitter_card_type = "summary",
twitter_site = "@JannisWrites"
),
shinyjs::useShinyjs(),
tabItems(
tabItem(tabName = "sample",
useShinyalert(),
h3("The Sample"),
bsAlert("dataAlert"),
fluidRow(
box(width = 12,
div(style="display:inline-block;width:100%;text-align:center;",
radioGroupButtons(
inputId = "var",
label = "Participant characteristics:",
selected = "languages",
status = "primary",
#justified = T,
#individual = T,
choiceNames = c("Survey language", "Gender", "Age", "Education", "Political orientation"),
choiceValues = c("languages", "gender", "age", "education", "political")
#checkIcon = list(yes = icon("ok", lib = "glyphicon"), no = icon("remove", lib = "glyphicon"))
)
),
h3(textOutput("sample.bar.NA"), align = "center"),
d3Output("d3.bar"),
textOutput("SampleTxt"), align = "center")
#)
),
fluidRow(
box(
status = "primary",
width = 6,
tags$strong("World Map (sample sizes of initial survey round)"),
highchartOutput("freqPlot")
),
box(
shinyjs::useShinyjs(),
id = "sample-controls",
width = 6,
#height = "600px",
title = "Controls",
solidHeader = T,
status = "primary",
#"Use these controls to ",
#br(),
multiInput(
inputId = "sample_country_selection",
label = "Please select the countries you are interested in (all countries n > 20):",
choices = NULL,
choiceNames = lapply(seq_along(ctry.only.red$coded_country),
function(i) tagList(tags$img(src = ctry.only.red$flag[i],
width = 20,
height = 15),
ctry.only.red$coded_country[i],
paste0(" (n=",prettyNum(ctry.only.red$n[i], big.mark=",", scientific=FALSE),")"))),
choiceValues = ctry.only.red$coded_country,
selected = all_valid_ctry
),
hr(),
div(style="display:inline-block;width:100%;text-align: center;",
actionBttn(
inputId = "sample_country_none",
label = "None",
style = "simple",
color = "primary",
size = "sm"),
HTML(" "),
actionBttn(
inputId = "sample_country_all",
label = "All",
style = "simple",
color = "primary",
size = "sm")
)
)
)
),
tabItem(tabName = "Variables",
box(width = 12, solidHeader = TRUE,
navbarPage(title = "Domain:",
id = "dataTabs",
tabPanel("Government Reponse",
value = 1,
highchartOutput("boxGov"),
"Note: Every person who took the survey could answer the above question. Here we present the average rating level (i.e., mean) of a given country,
as well as an interval that indicates the uncertainty around the average value given the sample (i.e., confidence interval).
Please keep in mind that (a) one country being higher or lower than another country can have a multitude of reasons (including the date in which they answered the question),
and (b) the data might not always be representative of the entire country’s population."
),
tabPanel("Community Response",
value = 2,
div(style="display:inline-block;width:100%;text-align: center;",
radioGroupButtons(
inputId = "ComVars",
#label = "",
selected = "comRule",
#justified = TRUE,
status = "primary",
choiceNames = c("Rules", "Punishment", "Organization"),
choiceValues = c("comRule", "comPunish", "comOrg")
#checkIcon = list(yes = icon("ok", lib = "glyphicon"), no = icon("remove", lib = "glyphicon"))
)
),
highchartOutput("boxCom"),
"Note: Every person who took the survey could answer the above question. Here we present the average rating level (i.e., mean)
of the countries you choose to select as well as an interval that indicates the uncertainty around the average value given the sample
(i.e., confidence interval - range of values that is likely to encompass the true value). Please keep in mind that
(a) one country being higher or lower than another country can have a multitude of reasons (including, when most people answered the question), and
(b) that the data might not always be representative the entire country."
),
tabPanel("Cognitive Response",
value = 3,
#Financial strain(?), job insecurity (?)",
div(style="display:inline-block;width:100%;text-align: center;",
radioGroupButtons(
inputId = "CogVars",
#label = "Variable:",
selected = "covidHope",
#justified = TRUE,
status = "primary",
choiceNames = c("Hope", "Efficacy", "Loneliness", "Paranoia", "Conspiracy"),
choiceValues = c("covidHope", "covidEff", "lone", "para", "consp")
#checkIcon = list(yes = icon("ok", lib = "glyphicon"), no = icon("remove", lib = "glyphicon"))
)
),
highchartOutput("boxCog"),
"Note: Every person who took the survey could answer the above question. Here we present the average rating level (i.e., mean)
of the countries you choose to select as well as an interval that indicates the uncertainty around the average value given the sample
(i.e., confidence interval - range of values that is likely to encompass the true value). Please keep in mind that
(a) one country being higher or lower than another country can have a multitude of reasons (including, when most people answered the question), and
(b) that the data might not always be representative the entire country."
),
tabPanel("Behavioral Response",
value = 4,
#"isolation, beh",
div(style="display:inline-block;width:100%;text-align: center;",
radioGroupButtons(
inputId = "BehVars",
#label = "Variable:",
selected = "behWash",
#justified = TRUE,
status = "primary",
choiceNames = c("Washing", "Avoiding", "Social Contact"),
choiceValues = c("behWash", "behAvoid", "iso")
)
),
htmlOutput("boxBeh"),
"Note: Every person who took the survey could answer the above question. Here we present the average rating level (i.e., mean)
of the countries you choose to select as well as an interval that indicates the uncertainty around the average value given the sample
(i.e., confidence interval - range of values that is likely to encompass the true value). Please keep in mind that
(a) one country being higher or lower than another country can have a multitude of reasons (including, when most people answered the question), and
(b) that the data might not always be representative the entire country."
),
tabPanel("Emotional Response",
value = 5,
column(12, align="center",
tags$b("Individual Emotions "),
prettySwitch(
inputId = "categorySwitch",
label = tags$b("Emotional Categories"),
status = "success",
fill = TRUE,
inline = TRUE,
value = FALSE
)
),
chartJSRadarOutput('affect', height = "125", width = "400"),
tags$br(),
"Note: Here you can see the emotional reactions of people. There are two ways to look at them: Emotional Categories and Individual Emotions.
For the individual emotions, people answered how much they felt that emotion over the last week. For the emotional categories, we averaged together
the emotions that are either high or low on arousal as well as positive or negative (negative high arousal: anxiety and nervous; negative low arousal:
bored, exhausted, depressed; positive high arousal: energetic, excited, inspired; positive low arousal: calm, content, relaxed)"
),
tabPanel("Cross Domain Relationships",
value = 6,
highchartOutput("cor"),
"Note: Here you can select two variables and plot them against each other. One bubble represents one country.
The bigger the bubble, the more people from that country answered the question. The position of the bubble represents the average levels of the variables
you select. This allows you to examine relationships between variables. For example, do countries that are higher in one variable also tend to be higher
on the other variable."
)
)
),
conditionalPanel(
condition = "input.dataTabs != 6",
box(width = 12,
solidHeader = T,
status = "primary",
multiInput(
inputId = "psych_country_selection",
label = "Please select the countries you are interested in (all countries n > 20):",
choices = NULL,
choiceNames = lapply(seq_along(ctry.red$coded_country),
function(i) tagList(tags$img(src = ctry.red$flag[i],
width = 20,
height = 15),
ctry.red$coded_country[i],
paste0(" (n=",prettyNum(ctry.red$n[i], big.mark=",", scientific=FALSE),")"))),
choiceValues = ctry.red$coded_country,
selected = "global"
)
)
),
conditionalPanel(
condition = "input.dataTabs == 6",
box(width = 12,
solidHeader = T,
status = "primary",
h4("Select Variables:"),
column(width = 6,
pickerInput(
inputId = "CorX",
label = "X Axis:",
#width = "80%",
choices = list(
Government = c("Clear Government Information" = "gov"),
Community = c("Rules"="comRule", "Punishment"="comPunish", "Organization"="comOrg"),
Cognitive = c("Hope"="covidHope", "Efficacy"="covidEff", "Loneliness"="lone", "Paranoia"="para", "Conspiracy"="consp"),
Behavior = c("Washing"="behWash", "Avoiding"="behAvoid", "Isolation Offline"="isoPers", "Isolation Online"="isoOnl"),
Emotion = c("Anxious"="affAnx", "Bored"="affBor", "Calm"="affCalm", "Content"="affContent", "Depressed"="affDepr", "Energetic"="affEnerg",
"Excited"="affExc", "Nervous"="affNerv", "Exhausted"="affExh", "Inspired"="affInsp", "Relaxed"="affRel"),
EmtionCat = c("High Arousal Positive"="affHighPos", "High Arousal Negative"="affHighNeg",
"Low Arousal Positive"="affLowPos", "Low Arousal Negative"="affLowNeg")
)
)
),
column(width = 6,
pickerInput(
inputId = "CorY",
label = "Y Axis:",
#width = "80%",
choices = list(
Government = c("Clear Government Information" = "gov"),
Community = c("Rules"="comRule", "Punishment"="comPunish", "Organization"="comOrg"),
Cognitive = c("Hope"="covidHope", "Efficacy"="covidEff", "Loneliness"="lone", "Paranoia"="para", "Conspiracy"="consp"),
Behavior = c("Washing"="behWash", "Avoiding"="behAvoid", "Isolation Offline"="isoPers", "Isolation Online"="isoOnl"),
Emotion = c("Anxious"="affAnx", "Bored"="affBor", "Calm"="affCalm", "Content"="affContent", "Depressed"="affDepr", "Energetic"="affEnerg",
"Excited"="affExc", "Nervous"="affNerv", "Exhausted"="affExh", "Inspired"="affInsp", "Relaxed"="affRel"),
EmtionCat = c("High Arousal Positive"="affHighPos", "High Arousal Negative"="affHighNeg",
"Low Arousal Positive"="affLowPos", "Low Arousal Negative"="affLowNeg")),
selected = "comPunish"
)
),
hr(),
h4("Select Region:"),
multiInput(
inputId = "cor_country_selection",
label = "Please select the countries you are interested in (all countries n > 20):",
choices = NULL,
choiceNames = lapply(seq_along(ctry.only.red$coded_country),
function(i) tagList(tags$img(src = ctry.only.red$flag[i],
width = 20,
height = 15),
ctry.only.red$coded_country[i],
paste0(" (n=",prettyNum(ctry.only.red$n[i], big.mark=",", scientific=FALSE),")"))),
choiceValues = ctry.only.red$coded_country,
selected = all_valid_ctry
),
div(style="display:inline-block;width:100%;text-align: center;",
actionBttn(
inputId = "cor_country_none",
label = "None",
style = "simple",
color = "primary",
size = "sm"),
HTML(" "),
actionBttn(
inputId = "cor_country_all",
label = "All",
style = "simple",
color = "primary",
size = "sm")
)
)
)
),
tabItem(tabName = "development",
#switch_sample = NULL,
#h2("Development over Time"),
navbarPage(id = "developmentPanel",
"Focus on:", #theme = shinytheme("flatly"),
tabPanel("Multiple countries",
#h2("Countries tab"),
bsAlert("longitudinalAlert"),
box(#title = "Explore The Data",
width = 12,
#heigth = "500px",
solidHeader = TRUE,
highchartOutput("long_ctrs_hc"),
tags$br()
),
box(width = 12,
solidHeader = T,
status = "primary",
#h4("Select Variables:"),
fluidRow(
column(width = 8, style = "margin-top: 6px;",
pickerInput(
inputId = "long_ctrs_var",
label = "Variable selection:",
#width = "80%",
choices = list(
Cognitive = c("Loneliness"="lone01", "Paranoia"="para01", "Conspiracy"="consp01"),
Behavior = c("Isolation Friends Offline"="isoFriends_inPerson", "Isolation Others Offline"="isoOthPpl_inPerson",
"Isolation Friends Online"="isoFriends_online", "Isolation Others Online"="isoOthPpl_online"),
Emotion = c("Anxious"="affAnx", "Bored"="affBor", "Calm"="affCalm", "Depressed"="affDepr", "Energetic"="affEnerg",
"Nervous"="affNerv", "Exhausted"="affExh", "Inspired"="affInsp", "Relaxed"="affRel")
)
)
),
column(width = 4, style = "margin-top: 0px;",
h5(tags$b("Confidence Interval:")),
switchInput(
inputId = "long_ctrs_CiSwitch",
onStatus = "success",
offStatus = "danger",
size = "mini",
value = FALSE
)
)),
hr(),
h4("Select Region:"),
multiInput(
inputId = "long_ctrs_country_selection",
label = "Please select the countries you are interested in (all countries with at least three weeks of n > 10):",
choices = NULL,
choiceNames = lapply(seq_along(weeklyRegions$coded_country),
function(i) tagList(tags$img(src = weeklyRegions$flag[i],
width = 20,
height = 15),
weeklyRegions$coded_country[i])),
choiceValues = weeklyRegions$coded_country,
selected = "global"
),
div(style="display:inline-block;width:100%;text-align: center;",
actionBttn(
inputId = "long_ctrs_none",
label = "None",
style = "simple",
color = "primary",
size = "sm"),
HTML(" "),
actionBttn(
inputId = "long_ctrs_all",
label = "All",
style = "simple",
color = "primary",
size = "sm")
)
)
),
tabPanel("Multiple Variables",
bsAlert("longitudinalAlert2"),
box(#title = "Explore The Data",
width = 12,
heigth = "500px",
solidHeader = TRUE,
highchartOutput("long_vars_hc"),
tags$br()
),
box(width = 12,
solidHeader = T,
status = "primary",
h4("Select Region:"),
fluidRow(
column(width = 8, style = "margin-top: 6px;",
pickerInput(inputId = "long_vars_country",
label = "country selection:",
#width = "80%",
choices = weeklyRegions$coded_country,
choicesOpt = list(content =
mapply(weeklyRegions$coded_country, weeklyRegions$flag, FUN = function(country, flagUrl) {
HTML(paste(
tags$img(src=flagUrl, width=20, height=15),
country
))
}, SIMPLIFY = FALSE, USE.NAMES = FALSE)),
selected = "global"
)),
column(width = 4, style = "margin-top: 0px;",
h5(tags$b("Confidence Interval:")),
switchInput(
inputId = "long_vars_CiSwitch",
onStatus = "success",
offStatus = "danger",
size = "mini",
value = FALSE
)
)),
hr(),
h4("Select Variable(s):"),
multiInput(
inputId = "long_vars_variables",
label = "Please select the variables you are interested in:",
choices = NULL,
choiceNames = c( "Anxious", "Bored", "Calm", "Depressed", "Energetic",
"Nervous", "Exhausted", "Inspired", "Relaxed",
"Loneliness", "Paranoia", "Conspiracy",
"Isolation Friends Offline", "Isolation Others Offline",
"Isolation Friends Online", "Isolation Others Online"),
choiceValues = mvars,
selected = "affAnx"
),
div(style="display:inline-block;width:100%;text-align: center;",
actionBttn(
inputId = "long_vars_none",
label = "None",
style = "simple",
color = "primary",
size = "sm"),
HTML(" "),
actionBttn(
inputId = "long_vars_all",
label = "All",
style = "simple",
color = "primary",
size = "sm")
)
)
)
),
),
tabItem(tabName = "data",
fluidRow(
box(title = "Data Protection",
width = 12,
solidHeader = TRUE,
HTML("To protect the privacy and confidentiality of our participants, this application only uses aggregate, anonymized data (i.e., no individual person is identifiable).
<br><b>Anonymization:</b><br>
<ol>
<li>We use <b>data aggregation</b> as the main method of data anonymization. This means that we never show data of a single person or small groups of people; instead,
we combine data of hundreds-to-thousands of people to show country-level summary statistics. As an example, you can see the average level of hope in a country and how much
variation there was in the responses, but you cannot see the rating of any individual respondent.
<br>Importantly, the application only has access to the country-level summaries, which means that data cannot be linked or combined to single out individuals
(e.g., you cannot see the level of hope for U.S. women, aged 25-34, who speak Farsi and have a doctorate degree).
<br><i>Note:</i> In order for aggregate data to be anonymous, we need to combine the responses of enough people. This is why we never display data of countries with less than 20 respondents.</li>
<li>When we show summaries of categorical data (e.g., percentage of people identifying as female), we additionally apply <b>data perturbations</b> for small groups. This means that the counts and percentages
for groups that comprise less than 20 people (less than 50 for political orientation) have been slightly changed (e.g., a random number between -2 and 2 or between -5 and 5 has been added;
this process is also sometimes referred to as 'artificial noise addition').
<br>Please note that this also means that the numbers are not always 100% accurate. However, with this method, we can represent the full diversity of our sample whilst still protecting the identities of people in
small or vulnerable groups.</li>
</ol>
These are the main ways in which we protect the personal data of our participants and make sure that no individual is identifiable within the application. If you have any questions or concerns, please feel
free to contact us at <a href=\"mailto:psycorona@rug.nl?Subject=Data%20web%20application\" target=\"_top\">psycorona@rug.nl</a>.
<br><b>Access:</b> <br>
Access to person-level data will never be made available without thorough vetting by our editorial board (see data sharing below). And even then, we only share
anonymized or pseudonymized data with active academic collaborators."),
tags$br(),
tags$br()
),
box(title = "Data Collaboration",
width = 12,
solidHeader = TRUE,
"One major aim of the PsyCorona initiative is to combine psychological reactions with local, regional,
and national data on the Covid-19 spread and governmental reactions. In our efforts we collaborate with ",
tags$a(href="https://dataversuscorona.com/",
target="_blank",
"Data Scientists Against Corona"),
"and are working on bringing together the ",
tags$a(href="https://github.com/cjvanlissa/COVID19_metadata",
target="_blank",
"Covid-19 Metadata"),
"repository with anonymized regional data from the PsyCorona initiative.",
tags$br(),
tags$br()
),
box(title = "Data Sharing",
width = 12,
solidHeader = TRUE,
"The aim of the PsyCorona initiative is to build a collaborative research network. If you are interested in becoming
part of the PsyCorona collaboration, you can contact us via our website: ",
tags$a(href="https://psycorona.org/",
target="_blank",
"www.psycorona.org."),
tags$br(),
tags$br(),
"Part of data sharing is also open availability of code. The code to this web applet is available at",
tags$a(href="https://github.com/JannisCodes/PsyCorona-WebApp",
target="_blank",
"our git repository."),
tags$br(),
tags$br()
)
)
),
tabItem(tabName = "about",
h3("Welcome to the PsyCorona Data Tool"),
br(),
fluidRow(
box(#title = "Explore The Data",
width = 8,
heigth = "500px",
solidHeader = TRUE,
h4("The Collaboration:"),
"Psychology and culture could affect the spread of the virus; human psychology could also change in response to the pandemic. Early in the pandemic,
we sought to mobilize behavioral and data scientists to identify psychological factors that could slow the spread of the pandemic and minimize its social damage.
All the scientists in the collaboration operate on a largely volunteer basis, relying on existing infrastructure and their own resources.
This is an international project based at New York University-Abu Dhabi and the University of Groningen (The Netherlands). We have evolved into a distributed team across the world,
with autonomous work groups in numerous countries, each of whom understands the PsyCorona mission goals and needs. We aim to ensure global involvement,
so we translated the survey into 30 languages and worked with more than 100 international social scientists to collect immediate and longitudinal information on
psychological factors that might predict the spread of COVID-19. Further details are available at the",
tags$a(href="https://www.psycorona.org",
target="_blank",
"PsyCorona website."),
br(),
"You can find the PsyCorona collaboration on: ",
tags$a(href="https://www.facebook.com/PsyCorona-100726584925027",
target="_blank",
icon("facebook")),
HTML(" "),
tags$a(href="https://github.com/JannisCodes/PsyCorona-WebApp",
target="_blank",
icon("github")),
br(),
br(),
h4("What You Can Do Here:"),
"This applet has ",
tags$b("four main interactive sections"),
" that enable visitors to directly interact with the PsyCorona data: ",
tags$ul(
tags$li("The ",
a("Data", onclick = "openTab('data')", href="#"),
"tab provides information on how we deal with our participants' data and how you can get involved in data analysis.
Here we also share information on our open-source code and on the connections to metadata repositories we aim to connect to the psychological responses.")),
"The remaining three tabs offer tools to visualize the psychological data we collect in this project.",
tags$ul(
tags$li("The ",
a("The Sample", onclick = "openTab('sample')", href="#"),
"tab offers an insight into the diversity of our participants. We share compound information on some demographic variables, as well as the number of respondents in each country.
Please note that to protect the privacy and anonymity of our participants, data visualizations are only available for selections of more than 20 people."),
tags$li("The ",
a("Psychological Variables", onclick = "openTab('Variables')", href="#"),
" tab offers an interactive interface to explore the psychological variables we collect in the initiative's baseline survey.
This survey is open to anyone interested at",
tags$a(href="https://nyu.qualtrics.com/jfe/form/SV_6svo6J4NF7wE6tD",
target="_blank",
"tiny.cc/corona_survey"),
"and currently includes over 50 000 participants. You can explore psychological reactions to the coronavirus at five different levels:
(1) Governmental Response, (2) Community Response, (3) Cognitive Response, (4) Behavioral Response, as well as (5) Emotional Response.
Additionally, we offer a tool to explore the mean level relationship between different variables for different countries. Please note that to protect the
privacy and anonymity of our participants we only provide country-level visualizations once we have data for more than 20 people from any particular country."),
tags$li("The ",
a("Development", onclick = "openTab('development')", href="#"),
" tab gives you the possibility to interactively explore how different areas are evolving over time. This section is currently partly under
construction, but will be fully available soon.")
)
),
box(width = 4,
HTML("<a class=\"twitter-timeline\" data-height=\"600\" href=\"https://twitter.com/FortuneMagazine/lists/coronavirus-updates?ref_src=twsrc%5Etfw\">A Twitter List by FortuneMagazine</a> <script async src=\"https://platform.twitter.com/widgets.js\" charset=\"utf-8\"></script>")
)
),
fluidRow(
valueBox(prettyNum(sum(world.n$n), big.mark=" ", scientific=FALSE), "Participants", icon = icon("user-edit"), width = 3),
valueBox(prettyNum(surveyN, big.mark=" ", scientific=FALSE), "Total Survey Responses", icon = icon("edit"), width = 3),
valueBox(sum(str_count(names(ctry.scales), c("language")))-1, "Languages", icon = icon("language"), width = 3),
valueBox("100+", "Researchers", icon = icon("user-graduate"), width = 3)#,
#valueBox(404, "Something", icon = icon("project-diagram"), width = 3)
)
)
)
)
)
# -----
server <- function(input, output, session) {
# -----
# observeEvent(input$dimension[1], {
# if (input$dimension[1] <= 767) {
# shinyalert(title = "Small Screen Detected",
# text = "Some elements of this application are not optimized for smaller screens.
# If you have problems viewing some of the graphical displays please try to use a desktop or tablet device with a larger screens.
# Some graphs might be visible if you use your device in landscape mode.",
# type = "info",
# animation = TRUE,
# confirmButtonCol = "#3b738f"
# )
# } else {
# }
# })
# shinyalert(title = "Preview Version",
# text = "This application is currently in development.
# To protect the privacy and confidentiality of our participants this beta version relies on simulated data.",
# type = "warning",
# animation = TRUE,
# confirmButtonCol = "#3b738f"
# )
createAlert(session = session,
anchorId = "dataAlert",
#alertId="a1",
title = paste(icon("warning"),"Data Notification"),
content="To protect the privacy of everyone who took our survey, this application only uses aggregate, anonymized data (i.e., no individual person is identifiable).
For further information, see our <a href='#' onclick=\"openTab('data')\">data description section</a>. Bear in mind that this display shows data collected during the first lockdown period (March through May 2020).
This means the data might not be representative of how countries are doing right now.
Where possible, we also provide <b> nationally representative, standardized, and developmental (longitudinal) displays of the data</b>.
You can find these options in the left sidebar.",
style = "warning")
createAlert(session = session,
anchorId = "longitudinalAlert",
#alertId="a1",
title = paste(icon("warning"),"Preliminary Data"),
content="You are beta testing this section. We aim to provide access to more data from more countries. However, to protect the privacy of our participants,
we will never release visualizations of data if we cannot be certain that the data are anonymous.
Additionally, standardized visualization options will be available soon for all developmental visualizations.",
style = "warning")
createAlert(session = session,
anchorId = "longitudinalAlert2",
#alertId="a1",
title = paste(icon("warning"),"Preliminary Data"),
content="You are beta testing this section. We aim to provide access to more data from more countries. However, to protect the privacy of our participants,
we will never release visualizations of data if we cannot be certain that the data are anonymous.
Additionally, standardized visualization options will be available soon for all developmental visualizations.",
style = "warning")
output$dynamic_content <- renderUI({
if (input$sidebarMenu == "sample") {
dyn_ui <- awesomeRadio(inputId = "switch_sample",
label = "Sample Selection:",
choices = c("Full sample" = "full",
"Representative sample" = "representative"),
selected = select_sample)
}
else if (input$sidebarMenu == "Variables") {
dyn_ui <- list(awesomeRadio(inputId = "switch_sample",
label = "Sample Selection:",
choices = c("Full sample" = "full",
"Representative sample" = "representative"),
selected = select_sample),
awesomeRadio(inputId = "switch_transformation",
label = "Transformation:",
choices = c("Raw data" = "raw",
"Standardized" = "standardized"),
selected = select_transformation)
)
}
else if (input$sidebarMenu == "development" && input$developmentPanel == "Multiple countries") {
dyn_ui <- awesomeRadio(inputId = "switch_transformation",
label = "Transformation:",
choices = c("Raw data" = "raw",
"Standardized" = "standardized"),
selected = select_transformation)
}
else if (input$sidebarMenu == "development" && input$developmentPanel == "Multiple Variables") {
dyn_ui <- disabled(awesomeRadio(inputId = "switch_transformation",
label = "Transformation:",
choices = c("Raw data" = "raw",
"Standardized" = "standardized"),
selected = "standardized"))
}
else {dyn_ui <- NULL}
return(dyn_ui)
})
output$sample.bar.NA <- renderText({
#input <- list(var = "language", sample_country_selection = c("France", "Germany"))
test <- reactive_ctry.scales() %>%
filter(coded_country %in% input$sample_country_selection) %>%
select(starts_with(input$var)) %>%
t() %>%
as.data.frame()
# colnames(test) <- input$sample_country_selection
test <- test %>%
mutate(n = rowSums(., na.rm=TRUE),
label = str_replace(rownames(.), ".*_", "")) %>%
filter(n>0,
label != "<NA>")
ifelse(sum(test$n)<20, "Not enough data to display summary","")
# ifelse(sum(test$n)<20, "","")
})
output$SampleTxt <- renderText({
#input <- list(var = "language", sample_country_selection = c("France", "Germany"))
explanation <- list(languages = "Note: The languages people used to answer the survey. Below, you can select the countries you are interested in.",
gender = "Note: The gender people identified with.",
age = "Note: The age of people who filled out the survey. ",
education = "Note: The education level of people who filled out the survey. ",
political = "Note: The political orientation of people who filled out the survey.")
explanation[[input$var]]
})
output$d3.bar <- renderD3({
#input <- list(var = "language", sample_country_selection = c("France", "Germany"))
#input <- list(var = "gender", sample_country_selection = c("Poland", "Romania", "Albania"))
dem <- reactive_ctry.scales() %>%
filter(coded_country %in% input$sample_country_selection) %>%
select(starts_with(input$var)) %>%
t() %>%
as.data.frame()
# colnames(dem) <- input$sample_country_selection
dem %>%
mutate(n = rowSums(., na.rm=TRUE),
label = str_replace(rownames(.), ".*_", "")) %>%
arrange(desc(n)) %>%
filter(n > 0,
label != "<NA>") %>%
mutate(y = n,
ylabel = scales::percent(n/sum(n), accuracy = 0.01), #prettyNum(n/sum(n)*100, big.mark = ",", format = "f", digits = 2),
fill = "#3b738f", #ifelse(label != input$val, "#E69F00", "red"),
mouseover = "#2a5674") %>%
r2d3(r2d3_file)
})
output$freqPlot <- renderHighchart({
hcmap(download_map_data = FALSE,
data = reactive_ctry.scales() %>% filter(coded_country %in% input$sample_country_selection),
#data = ctry.only.red,
value = "n",
joinBy = c("iso-a2", "iso_a2"), name = "sample size",
#dataLabels = list(enabled = TRUE, format = '{point.name}'),
borderColor = "#FAFAFA", borderWidth = 0.1,
tooltip = list(valueDecimals = 0, valuePrefix = "n = "),
margin = 0) %>%
hc_mapNavigation(enabled = TRUE) %>%
hc_colorAxis(minColor = "#c4e6c3", maxColor = "#1d4f60", type = "logarithmic", endOnTick=FALSE, maxPadding=0)
})
#Color schemes: https://carto.com/carto-colors/