-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintro_rshiny.html
executable file
·1120 lines (833 loc) · 33.9 KB
/
intro_rshiny.html
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
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>MAT381E-Week 13-14: Building Interactive Web Applications</title>
<meta charset="utf-8" />
<meta name="author" content="Gül İnan" />
<meta name="date" content="2022-01-09" />
<script src="intro_rshiny_files/header-attrs-2.11/header-attrs.js"></script>
<link href="intro_rshiny_files/remark-css-0.0.1/default.css" rel="stylesheet" />
<script src="intro_rshiny_files/fabric-4.3.1/fabric.min.js"></script>
<link href="intro_rshiny_files/xaringanExtra-scribble-0.0.1/scribble.css" rel="stylesheet" />
<script src="intro_rshiny_files/xaringanExtra-scribble-0.0.1/scribble.js"></script>
<script>document.addEventListener('DOMContentLoaded', function() { window.xeScribble = new Scribble({"pen_color":["#FF0000"],"pen_size":3,"eraser_size":30,"palette":[]}) })</script>
<link href="intro_rshiny_files/tile-view-0.2.6/tile-view.css" rel="stylesheet" />
<script src="intro_rshiny_files/tile-view-0.2.6/tile-view.js"></script>
<link href="intro_rshiny_files/animate.css-3.7.2/animate.xaringan.css" rel="stylesheet" />
<link href="intro_rshiny_files/tachyons-4.12.0/tachyons.min.css" rel="stylesheet" />
<link href="intro_rshiny_files/panelset-0.2.6/panelset.css" rel="stylesheet" />
<script src="intro_rshiny_files/panelset-0.2.6/panelset.js"></script>
<link rel="stylesheet" href="xaringan-themer.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: left, middle, my-title, title-slide
# MAT381E-Week 13-14: Building Interactive Web Applications
### Gül İnan
### Department of Mathematics<br/>Istanbul Technical University
### January 9, 2022
---
class: left
# Outline
* Introduction to `Shiny` package.
* Examples.
---
- Please visit the [NASA Earth Data's Covid-19 Dashboard](
https://earthdata.nasa.gov/covid19/explore/be?map=116.345%2C39.9954%2C8.94&date=2021-02-01&lState=nightlights-hd%7C0%7C0).
<img src="images/nasa.png" width="100%" />
---
class: center, middle
<img src="logo/rshiny.png" width="35%" />
---
#### Shiny package
- [R Shiny](https://shiny.rstudio.com/) is an `R` package that provides elegant and powerful web framework for **building interactive web applications (apps)** directly from `R`.
- You can host standalone apps on a **webpage** or build **dashboards**.
- Shiny applications are automatically live and outputs change instantly as users modify inputs, without requiring a reload of the browser.
- You can also extend your Shiny apps with [CSS themes](http://rstudio.github.io/shinythemes/?_ga=2.128822476.1106871023.1621587722-51308884.1621587722), [htmlwidgets](http://www.htmlwidgets.org/), and [JavaScript](https://github.com/daattali/shinyjs/blob/master/README.md) actions.
- To install and load the package:
```r
#install.packages("shiny")
library(shiny)
```
---
- Let's see a few quick **built-in** `R Shiny` examples available:
```r
library(shiny)
runExample("01_hello") # a histogram # slider widget
```
```r
library(shiny)
runExample("02_text") # tables and data frames #select box and numeric input widgets
```
```r
library(shiny)
runExample("06_tabsets") # tabbed panels #radio buttons and slider widgets
```
---
- Here is how `R Shiny` works at first sight:
<img src="images/basic_structure.png" width="60%" />
---
#### Create a Demo App
- In `RStudio`, go to `File` menu, choose `New Project`.
- You will see a pop-up window like the one below. Choose `New Directory`.
<img src="images/new_project_wizard.png" width="60%" />
---
- Choose `Shiny Web Application` as the project type.
<img src="images/shiny_web.png" width="60%" />
---
- Give a `directory name` such as `demo` for your app and save it.
<img src="images/directory.png" width="60%" />
---
- Your `RStudio interface` should look like below now.
- Click on `Run App` in the top right corner of the `source pane`.
<img src="images/interface.png" width="80%" />
---
- The app will open up in a new window.
- Play with the `slider` and watch the histogram change.
<img src="images/demo_app.png" width="60%" />
- We can also open up the app in a web browser by clicking on `Open in Browser`.
---
#### Shiny app structure
- Now go back to `app.R`, which is the source code of `Shiny` app.
- We can see that `Shiny` app:
- calls `library(shiny)` to load the shiny package,
- has a `ui` (short for user interface) component which defines how the app looks,
- has a `server` function which defines how the app works, and
- executes `shinyApp(ui, server)` function to construct and start a `Shiny app` from `ui` and `server`.
```r
library(shiny)
ui <- fluidPage()
## fluidPage {shiny}: Functions for creating fluid page layouts.
## A fluid page layout consists of rows which in turn include columns.
## Rows exist for the purpose of making sure their elements appear
## on the same line (if the browser has adequate width).
##Other layout functions: fillPage(), fixedPage(), flowLayout(),
##navbarPage(), sidebarLayout(), splitLayout(), verticalLayout()
server <- function(input, output) {}
shinyApp(ui = ui, server = server)
```
---
#### User Interface (UI) structure
- The `ui` part of `Shiny` app includes a few new functions:
- [fluidPage()](https://shiny.rstudio.com/reference/shiny/0.14/fluidPage.html): is a layout function that sets up the basic visual structure of the page.
- `titlePanel()`: for title of the panel.
- [sidebarLayout()](https://shiny.rstudio.com/reference/shiny/0.14/sidebarLayout.html): for providing a sidebar for inputs and a large main area for output.
```r
# Define UI for application
ui <- fluidPage(
# Application title
titlePanel("Panel Title"),
# Application main window
sidebarLayout(
# Application sidebar panel appearance
# The sidebarPanel() containing input controls.
sidebarPanel(
#####Input widgets come here
),
# Main panel as output
# The mainPanel() containing outputs.
mainPanel(
#####Output comes here
)
)
)
```
---
#### Re-visit demo app
- By default, the sidebar takes up 1/3 of the width, and the main panel 2/3.
<style type="text/css">
.pull-left {
float: left;
width: 48%;
}
.pull-right {
float: right;
width: 48%;
heigth: 100%;
}
</style>
.pull-left[
```r
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
# Sidebar with a slider input for number of bins
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
```
]
--
.pull-right[
<img src="images/ui.png" width="100%" />
]
---
- In the `ui`, the function `sidebarPanel()` draws the panel for sidebar, whereas the function `mainPanel()` draws the main output panel.
<img src="images/ui_output.png" width="90%" />
---
- The function `sidebarPanel()` takes the input, and then the output is produced based on the input value in the sidebar panel.
- The `sliderInput()` tells us that **input widget** is a horizontal slider which has a single handle that can be moved with the mouse.
- The `plotOutput()` tells us that the produced output will be a plot.
<style type="text/css">
.pull-left {
float: left;
width: 48%;
}
.pull-right {
float: right;
width: 48%;
heigth: 100%;
}
</style>
.pull-left[
```r
ui <- fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
# Sidebar with a slider input for number of bins
sidebarPanel(
# sliderInput(inputId,
# label,
# min,
# max,
# value)
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
```
]
--
.pull-right[
<img src="images/ui.png" width="100%" />
]
---
#### ui input widgets
- `Shiny` comes with a variety of built in **input widgets** such as:
<img src="images/input_widgets.png" width="70%" />
---
- Visit the [Shiny widget gallery](https://shiny.rstudio.com/gallery/widget-gallery.html) for all possible input widgets and their usage.
---
#### ui outputs
- `Shiny` provides a family of functions that turn `R objects` in `server()` into output for `ui`.
- Each function below creates a specific type of output for `ui`.
|Output function |Creates |
|----------------------- |-------------|
|<span style="color:blue">plotOutput()</span> | Plot. |
|<span style="color:blue">tableOutput()</span> | Table. |
|<span style="color:blue">dataTableOutput()</span> | DataTable. |
|`htmlOutput()` | Raw HTML. |
|`imageOutput()` | Image. |
|`textOutput()` | Text. |
|`uiOutput()` | Raw HTML. |
|`verbatimTextOutput()` | Text. |
---
#### Server structure
- Next, we need to provide the `R code` in the `server()` function to build the output in the `ui`.
- The `server()` builds a **list-like** **output** and **input** objects that contains all of the code needed to update the `R objects` in our app.
- Each `R` object needs to have its own entry in the list.
---
#### Re-visit demo app
- We can create an entry by defining a new element for `output` within the `server` function, like below.
- The element name should match the name of the **reactive element** that we created in the `ui`.
```r
# Define server logic required to draw a histogram
server <- function(input, output) {
# generate the histogram plot output
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
```
---
- Each entry to `output` in `server` should contain one of `render*()` functions.
- Use the `render*()` function that corresponds to the type of **reactive object** you are making.
|Render function |Creates |
|-----------------------|-------------------------------------------------|
| <span style="color:blue">renderPlot()</span> | Plots. |
| <span style="color:blue">renderTable()<span style="color:blue"> | Data frame, matrix, other table like structures.|
| <span style="color:blue">renderDataTable()<span style="color:blue"> | DataTable. |
| `renderImage()` | Images (saved as a link to a source file). |
| `renderPrint()` | Any printed output. |
| `renderText()` | Character strings. |
| `renderUI()` | A Shiny tag object or HTML. |
- Each `render*()` function takes a single argument: an `R expression` surrounded by braces {} and do some light pre-processing on the expression.
---
- The `R expression` can be one simple line of text, or it can involve many lines of code, as if it were a complicated function call.
- For this to work, your expression should return the object you have in mind (a piece of text, a plot, a data frame, etc.). You will get an error if the expression does not return an object, or if it returns the wrong type of object.
---
- The outputs in `render*()` of `server` and `*Output()` in `ui` together.
<img src="images/compatibility.png" width="70%" />
---
- Match the input and output objects in `ui` and `server`.
.pull-left[
```r
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
# Sidebar with a slider input for number of bins
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
```
]
.pull-right[
```r
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
```
]
- `input$id` = bins & `output$id` = distPlot. Output is a plot object.
---
#### Run the app: UI + Server
- When ready, launch your `Shiny app` by running:
```r
# Run the application
shinyApp(ui = ui, server = server)
```
---
#### Data
- We have a data set named **countries_1998_2011.csv** which is all about a Human Development Index calculated by [United Nations Development Programme](http://hdr.undp.org/en/content/human-development-index-hdi).
- <span style="color:purple">**The Human Development Index (HDI)** is a summary measure of average achievement in key dimensions of human development: a long and healthy life, being knowledgeable and have a decent standard of living. The HDI is the geometric mean of normalized indices for each of the three dimensions.</span>
<img src="images/hdi_index.png" width="100%" />
- [GINI Index](https://www.census.gov/topics/income-poverty/income-inequality/about/metrics/gini-index.html).
- [Why geometric mean used in HDI rather than arithmetic mean?](http://hdr.undp.org/en/content/why-geometric-mean-used-hdi-rather-arithmetic-mean)
---
class: middle, center
<img src="images/hdi.png" width="100%" />
[Source](http://hdr.undp.org/en/content/human-development-index-hdi)
---
- The data set **countries_1998_2011.csv** is available under `data directory`. Please, have a look at it.
- Note that this is an old data set I have found on an arbitrary webpage. For that reason, I am not able to give you the original url address.
```r
library(tidyverse)
data <- read_csv("data/countries_1998_2011.csv")
head(data)
```
```
#> # A tibble: 6 × 10
#> country country_code continent sub_region year human_development…
#> <chr> <chr> <chr> <chr> <dbl> <dbl>
#> 1 Afghanistan AFG Asia Southern Asia 1998 0.335
#> 2 Albania ALB Europe Southern Europe 1998 0.646
#> 3 Algeria DZA Africa Northern Africa 1998 0.627
#> 4 Angola AGO Africa Sub-Saharan Africa 1998 NA
#> 5 Argentina ARG Americas Latin America and… 1998 0.753
#> 6 Armenia ARM Asia Western Asia 1998 0.632
#> # … with 4 more variables: corruption_perception_index <dbl>, population <dbl>,
#> # life_exp <dbl>, gdp_per_capita <dbl>
```
```r
View(data)
```
---
#### Example: Countries-01
- Filter the data for the year 2011 and develop a `Shiny` app which enables to select one of variables **human_development_index**, **corruption_perception_index**, **population**, **life_exp**, and **gdp_per_capita** through an `input widget` to plot the selected variable on the horizontal axis and also enables to select another variable through another `input widget` to plot that selected variable on the vertical axis.
- Afterwards, get a scatter plot of the selected two variables and identify the points by their **continent type** by assigning different **colors**.
---
class: middle, center
<img src="images/fig1.png" width="100%" />
---
class: middle, center
<img src="images/fig2.png" width="100%" />
---
#### SelectInput Widget
- This question requires to use the `selectInput` widget in the `ui`:
- **Usage**:
```r
selectInput(
inputId,
label,
choices,
selected = NULL
)
```
- **Arguments**:
- `inputId`: The input slot that will be used to access the value.
- `label`: Display label for the control, or NULL for no label.
- `choices`: List of values to select from.
- `selected`: The initially selected value.
- **Value**: A select list control that can be added to a UI definition.
---
⚠️ Not happy with axis labels? Please read the help page below:
https://community.rstudio.com/t/reactive-axis-labels-in-shiny-with-ggplot-display-user-selected-label-not-variable-name/17560
---
#### Example: Countries-02
- Now, add a third **select variable** for **point size** in the scatter plot with choices "population", "life_exp", "gdp_per_capita".
- Use this variable in the aesthetics of the `ggplot` function as the `point size` argument.
<img src="images/point_size.png" width="100%" />
---
#### Example: Countries-03
- Add a **SliderInput** with range [0-1] with a **default value** at 0.8.
- Pass this variable to the `alpha` argument in the `geom_point()` function.
<img src="images/transparency.png" width="100%" />
---
#### SliderInput Widget
- This question requires to use the `sliderInput` widget in the `ui`:
- **Usage**:
```r
sliderInput(
inputId,
label,
min,
max,
value
)
```
- **Arguments**:
- `inputId`: The input slot that will be used to access the value.
- `label`: Display label for the control, or NULL for no label.
- `min`: The minimum value (inclusive) that can be selected.
- `max`: The maximum value (inclusive) that can be selected.
- `value`: The initial value of the slider.
---
#### Example: Countries-04
- Create a table showing **countries_data_2011** data set.
<img src="images/table.png" width="100%" />
---
#### DT: An R interface to the DataTables library
- The `R` package [DT](https://rstudio.github.io/DT/) provides an `R` interface to the `JavaScript` library [DataTables](https://datatables.net/).
- `R` data objects (matrices or data frames) can be displayed as tables on `HTML` pages, and `DataTables` provides filtering, pagination, sorting, and many other features in the tables.
- Our question requires to use the `DT::dataTableOutput` widget in the `ui` along with
`DT::renderDataTable` in the `server`.
- We also need to include `library(DT)` at the beginning of the code.
---
#### Example: Countries-05
- Add a `checkboxInput` widget and
the value of the checkbox inside `DT::renderDataTable()` to **show/hide** the data table.
<img src="images/show_table.png" width="100%" />
---
#### checkboxInput widget
- This question requires to use the `checkboxInput` widget in the `ui`:
- **Usage**:
```r
checkboxInput(inputId,
label,
value = TRUE)
```
- **Arguments**:
- `inputId`: The input slot that will be used to access the value.
- `label`: Display label for the control, or NULL for no label.
- `value`: The initial value.
---
#### Example: Countries-06
- Add interactivity to the plot.
<img src="images/plotly.png" width="100%" />
---
#### R package plotly
<img src="images/plotly_book.png" width="95%" />
[Source](https://plotly-r.com/index.html)
---
#### plotly: An R interface to the plotly library
- The R package [plotly](https://plotly-r.com/index.html) provides an R interface to the Javascript library [plotly](https://plotly.com/javascript/).
- This question requires to use the `plotly::plotlyOutput` in the `ui` along with
`plotly::renderPlotly` in the `server`.
- We have already had a `ggplot` object, we can turn it into a `plotly` object via `ggplotly()` function.
- We also need to include `library(plotly)` at the beginning of the code.
---
#### Reactivity
- **Reactivity** is the relationship between **reactive values** and **reactive functions**: reactive values triggers reactive functions, and let the app instantly update itself whenever the user makes a change.
- Main reactive functions in `Shiny` is:
- `render*({})`: creates reactivity by using `input$*` inside `render*({})` functions.
- `reactive({})`: builds a reactive expression (behaves like the input$*).
---
#### Example: Countries-07
- How would you plot a subset of data corresponding to a certain year?
<img src="images/subset_reactive.png" width="100%" />
---
- Add a `UI` widget element for the user to select the year.
```r
## add select variable for year
selectInput(inputId = "year",
label = "Year",
choices = unique(countries_data$year),
selected = 2011)
```
---
- Filter the selected year and return a new dataframe as a **reactive expression** via
`reactive({})`.
```r
## filter data based on the selected year
countries_subset <- reactive({
countries_data %>%
filter(year == input$year)
})
```
---
- Use the new dataframe for plotting.
```r
## create scatter plot
output$countries_scatter <- renderPlotly({
p_scatter <- ggplot(data = countries_subset(),
aes_string(....))+
geom_point(....)
....
ggplotly(p_scatter)
})
```
---
- - Use the new dataframe for printing the table.
```r
## create data table -------------------------------------
output$countries_table <- renderDataTable({
if(input$show_table){countries_subset()}
})
```
---
#### Example: Countries-08
- Create a new reactive **countries_summary** as a new dataframe with median **gdp_per_capita** and **median life_exp per continent**.
- Modify `DT::renderDataTable` to use **countries_summary**.
<img src="images/summary_table.png" width="100%" />
---
#### Example: Countries-09
- Revisit the latest countries example and present "Plot" and "Data Table" as **panel sets**.
.pull-left[
<img src="images/tabset1.png" width="100%" />
]
.pull-right[
<img src="images/tabset2.png" width="100%" />
]
---
- This question requires to use the `tabsetPanel()` function in the `ui`.
- Tabsets are useful for dividing output into multiple independently viewable sections.
- **Usage**:
```html
tabsetPanel(type="tabs",
tabPanel(title, ...)
)
```
- **Arguments**:
- `type="tabs"`: Standard tab look
- `tabPanel`: Create a tab panel that can be included within a `tabsetPanel()`.
- `title`: Display title for tab.
- ...: UI elements to include within the tab.
- There can be multiple `tabPanel()`'s in a `tabsetPanel()`.
---
```r
tabsetPanel(type = "tabs",
tabPanel(title = "Plot",
plotlyOutput(outputId = "countries_scatter")),
tabPanel(title = "Data",
dataTableOutput(outputId = "countries_table"))
)
```
---
#### htmltools package tags
- We can also embed `HTML` tags into `ui` part of our `Shiny` app.
- Tags should start with `tags` function.
- Here is the complete tag list available in `htmltools` package.
```r
#install.packages(htmltools)
library(htmltools)
names(tags)
```
---
- The most commonly used `HTML` tags are:
|R function |HTML |
|------------------|---------------------|
|`h1()`,...,`h6()` | Headers. |
|`p()` | Paragraph. |
|`em()` | Italic text. |
|`strong()` | Bold text. |
|`span()` | Text color. |
|`a()` | Hyperlink. |
|`br()` | Line break. |
|`img()` | Embed image. |
|`iframe()` | Embed Video. |
- More info at https://shiny.rstudio.com/articles/tag-glossary.html.
---
#### Visit hmtl_tag_example for full code
```r
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
## Main header
tags$h1("My First Shiny App"),
tags$p(" I love data science."),
## Un-ordered list
tags$ul(
tags$li("Tidyverse"),
tags$li("Rvest"),
tags$li("Shiny")
),
## Tags can be nested.
tags$p(
"The link to the Shiny website is",
tags$a(href = "https://www.rstudio.com/shiny/", "rstudio.com/shiny."),
tags$strong("I strongly recommend that you take a look at it!")
),
## Some line break.
tags$br(),
## Include image.
tags$img(src="https://i.vimeocdn.com/video/776716658.webp?mw=1100&mh=619&q=70", width="200", height="200"),
## Some line break.
tags$br(),
tags$span(style="color:purple", "Have a good winter break!..")
)
# Define server logic required to draw a histogram
server <- function(input, output) {
}
# Run the application
shinyApp(ui = ui, server = server)
```
---
#### Shiny themes
- The default theme of `Shiny` is **Bootstrap theme**.
- However, we can also easily change the overall appearance of the Shiny application using the R package [shinythemes](https://rstudio.github.io/shinythemes/).
- Install:
```r
install.packages("shinythemes")
```
- The possible theme names at https://rstudio.github.io/shinythemes/: cerulean, cosmo, cysborg, darkly, superhero.
- Then, in the `ui`, add `shinytheme("theme name")` to the `fluidPage()` function:
```r
## ui.R ##
library(shinythemes)
fluidPage(theme = shinytheme("superhero"),
...
)
```
---
#### Dash Boards
- You can turn your `Shiny app` completely into a Dash Board.
<img src="images/dashboard.png" width="60%" />
- Visit [Shiny Dash Board](https://rstudio.github.io/shinydashboard/index.html)
for details.
- Visit also https://github.com/turgayh/Interactive-Migration-Map and
https://taylanbt.shinyapps.io/interactive_turkey_map_-_migration/ for an earlier student project.
---
#### Sharing Shiny apps
<img src="images/deploy1.png" width="60%" />
[Source](https://shiny.rstudio.com/deploy/)
---
#### Shiny Contest
<img src="images/contest.png" width="60%" />
[Source](https://blog.rstudio.com/2021/03/11/time-to-shiny/)
---
class: middle, center
#### GitHub Pages
<iframe width="853" height="480" src="https://www.youtube.com/embed/2MsN8gpT6jY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
- Source on [deploying a react app on Github pages](https://medium.com/mobile-web-dev/how-to-build-and-deploy-a-react-app-to-github-pages-in-less-than-5-minutes-d6c4ffd30f14).
---
#### Vulnerability index (at home)
- Visit the `Shiny` app source code on **vulnerability** at https://github.com/BPSTechServices/vulnerability_weighting_map.
<img src="images/vulnerability.png" width="80%" />
[Source](https://github.com/BPSTechServices/vulnerability_weighting_map)
---
- **Vulnerability index** in a community is calculated as a composite index across following indicators:
- **Education**: The share of adults who do not have a four-year degree (**pct_noba** variable).
- **Tenure**: The share of households who rent their home (**pct_rent** variable).
- **Race**: The share of the population identifying as a person of color (**pct_poc** and **pct_underserved_poc**variables).
- **Income**: The share of households that earn less than 80% of the median family income (MFI)(**median_hh_inc** variable).
- **Age**: The share of people over 70 (**pct_over_70** variable).
- **Nutrition**: The share of people (or households) receiving food assistance (**pct_food_stamps** variable).
- **Computer**: The share of people who has no access to computer (**pct_no_device** variable).
```r
vulnerability <- readRDS("data/acs_vuln_weighting_data.rds")
View(vulnerability)
class(vulnerability)
```
---
- Look at the subset data.
```r
subset <- vulnerability %>%
select("GEOID", "NAME", "pct_noba",
"pct_rent", "median_hh_inc", "pct_poc",
"pct_underserved_poc","pct_over_70",
"pct_food_stamps", "pct_no_device",
"in_primary_place")
View(subset)
```
```r
usage <- cbind(subset$GEOID, subset$NAME, subset$pct_noba,ntile(subset$pct_noba, 100)) %>% View()
```
---
- Based on this data, create `radioButtons` widget for **in_primary_place** variable, then based
on this selection, create `SliderInput` widgets for "pct_noba", "pct_rent", "median_hh_inc", "pct_poc",
"pct_underserved_poc","pct_over_70", "pct_food_stamps", "pct_no_device" which are changing between 0 and 5.
---
# Attributions
- https://curso-r.github.io/my-first-dashboard-with-shiny-csds2019/#50
- https://psyteachr.github.io/shiny-tutorials/01-first-app.html
- https://github.com/OmaymaS/intro_to_shiny_workshop/tree/master/slides
- https://shiny.rstudio.com/tutorial/
- https://mastering-shiny.org/basic-app.html
- http://zevross.com/blog/2016/04/19/r-powered-web-applications-with-shiny-a-tutorial-and-cheat-sheet-with-40-example-apps/
- https://deanattali.com/blog/building-shiny-apps-tutorial/
- https://github.com/carlos-alberto-silva/weblidar-treetop
- https://infographics.economist.com/2021/job-interactive-data-journalist/
---
class: middle, center
<span style="color:purple">WISH YOU A GOOD FINAL EXAM WEEK & WINTER BREAK!..</span>
<br>
✏️ 📚 ☃️
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script src="assets/remark-zoom.js"></script>
<script src="https://platform.twitter.com/widgets.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "github",
"highlightLines": true,
"countIncrementalSlides": false,