generated from inSilecoInc/workshop_R_template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_01_shiny_intro.Rmd
794 lines (500 loc) · 14.5 KB
/
_01_shiny_intro.Rmd
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
---
title: "Intro Shiny"
output:
xaringan::moon_reader:
css: [default, rd.css, rd-font.css, "hygge"]
lib_dir: assets
seal: false
nature:
highlightStyle: dracula
countIncrementalSlides: false
beforeInit: "macros.js"
---
```{r include = FALSE}
source("_setup.R")
htmltools::tagList(
xaringanExtra::use_clipboard(
button_text = "<i class=\"fa fa-clipboard\"></i>",
success_text = "<i class=\"fa fa-check\" style=\"color: #37abc8\"></i>",
),
rmarkdown::html_dependency_font_awesome()
)
lg_shiny <- function(width) {
glue("<img src='https://raw.githubusercontent.com/rstudio/shiny/master/man/figures/logo.png'
alt='Siny logo' width='{width}%' style='vertical-align:middle'>")
}
```
class: inverse, center, middle
# `r nf()` Introduction to Shiny
![:custom_hr]()
---
class: inverse, center, middle
# General introduction
![:custom_hr]()
---
# Shiny applications
## `r rfa("comments")` What is Shiny?
## `r rfa("comments")` What do you want to use it for?
## `r rfa("comments")` Have you already built a Shiny App?
---
# Shiny applications
## What for?
--
### - apps are cool and can be useful
### - interactive capabilities
### - micro-meso web applications tailored to our needs
--
## Why not another technology?
--
### - because it's very powerful
### - because we are `r rp()` users!
- you only need to know `r rp()` (at least for start)
- design for our community
- use tools (packages) you already know
---
# Shiny is a package
.pull-left[
### An `r rp()` package developed by [Posit](https://posit.co/)
[`shiny`](https://cran.r-project.org/package=shiny) .font90[12/2012 (0.2.3) `r ar()` 10/2022 (1.7.3)]
]
.pull-right[
.left[[`r lg_shiny(24)`](https://cran.r-project.org/package=shiny)]
]
> [`shiny`](https://cran.r-project.org/package=shiny) makes it incredibly easy to build interactive web applications with R. Automatic "reactive" binding between inputs and outputs and extensive prebuilt widgets make it possible to build beautiful, responsive, and powerful applications with minimal effort.
--
```R
install.packages("shiny")
library("shiny")
packageVersion("shiny")
[1] ‘1.7.3’
```
* https://github.com/rstudio/shiny/blob/main/NEWS.md
???
I's an R package
we wont go over details of new feature but important to have latest (minor) version
---
# Shiny is a framework to create apps
.pull-left[
<img src="https://d33wubrfki0l68.cloudfront.net/0c97eee3d8fc820f3a8d670c08b286e8a524257b/e426c/cover.png" alt="" width="80%">
`r bk()` [Mastering Shiny](https://mastering-shiny.org/)
]
--
.pull-right[
> .font90[Shiny is a framework for creating web applications using R code. It is designed primarily with data scientists in mind, and to that end, you can create pretty complicated Shiny apps with no knowledge of HTML, CSS, or JavaScript.]
* You create the **frontend** and the **backend** with `r rp()`
]
---
# Backend vs Frontend
- Major distinctions in web applications
--
* __Frontend__: what you see, refers to the interface
--
* __Backend__: what's happening on the server (remote computer)
--
- With Shiny you are using `r rp()` to create both:
* `r ey()` Frontend (User interface)
* what you will see
* where inputs and outputs are displayed
* `ui`: an **object** (a tag list, includes HTML content)
* `r cg()` Backend
* the rules that link inputs and outputs
* `server`: a **function**
---
# UI vs Server
## UI (Frontend) :
- what users will interact with (operation are done inside your web browser, so on your computer)
- `r rfa("html5")` HTML, `r rfa("css3")` CSS, `r rfa("js")` JavaScript
- via `r rp()` (partially or entirely)
--
## Server (Backend) :
- the operations done under the hood on a remote computer (a server).
- basically `r rp()` (running on the remote computer)
- other languages via `r rp()`
--
### `r tr()` inspector will show you HTML, CSS and JavaScript, not `r rp()` code,
### `r tr()` when you are developing the app, the server is your computer!
---
# Shiny has its own ecosystem
### Not just one package!
--
### See https://shiny.rstudio.com/
### See RStudio's [Shiny apps gallery](https://shiny.rstudio.com/gallery/) for many examples.
### List of resources: [awesome-shiny-extensions](https://github.com/nanxstats/awesome-shiny-extensions)
---
# Shiny pros and cons
## Pros
- Use all `r rp()`'s capabilities (data analysis, visualization, etc.) in a Web application!
--
- Takes no time to build a simple (yet personalized) application.
--
- Applications can be run locally, deployed on R Studio's [Shiny Server](https://rstudio.com/products/shiny/shiny-server/), or to a hosting service such as [shinyapps.io](https://shinyapps.io), or your own server.
--
- Extensive documentation and material available for shiny applications.
--
- As often with `r rp()`, one of the major strength is the community: (academics / researchers)
--
- Growing bigger and bigger, getting better and better
---
# Shiny pros and cons
## Cons
- Syntax and logic of a Shiny application is a little bit different than what we are usually used to with `r rp()`.
--
- Takes some time to learn, require a more complex mental model.
--
- Harder to troubleshoot (at least when we start).
--
- Because it is more complex (another layer), it is worthwhile to really ponder whether a shiny application is necessary for what we wish to accomplish. _"Do you really need it?"_
---
# Shiny, an example `r lc()`
## Spatial reporting tool
### **Bedford Institute of Oceanography, DFO**
* `r gh()` https://github.com/inSilecoInc/shinySpatialApp_origin
--
* `r gh()` https://github.com/dfo-mar-odis/shinySpatialApp
* `r lk()` https://github.com/AtlanticR/reproducible-rap-report/blob/main/TechReport-AfterReview.pdf.pdf
---
class: inverse, center, middle
# `r nf()` Reactive programming
![:custom_hr]()
---
# Reactive programming
## Why?
`r lc()` [Simple shiny app](https://shiny.rstudio.com/gallery/single-file-shiny-app.html)
--
* When I change `Number of obs` to `n` then :
- `n` new values are drawn,
- a new histogram is generated and displayed
--
* **reactivity**!
- **reactive programming** = **event-driven programming** the event is "data has changed" (think "spreadsheet")
- see [this answer on `r rfa("stack-overflow")`](https://stackoverflow.com/questions/34495117/how-is-reactive-programming-different-than-event-driven-programming),
---
# Reactive programming
- That's the tricky part! As `r rp()` users we do not use **reactive programming**.
--
- we are familiar with different paradigms:
- **imperative programming**: "do this"
- **functional programming**: we create and call functions
- **array programming**: we apply operations on vectors
- ...
--
- ... but not **reactive programming** that is more **declarative**: "make sure that this is done"
---
# Reactive programming
## Making lemonade...
--
- with **imperative programming**:
> "pour 1 L of cold water, stir in 30 mL of lemon juice and add 1 tablespoon of map syrup"
--
- with **declarative programming**:
> "you have 1 L of cold water, 30 mL of lemon juice and 1 tablespoon of map syrup, make me a lemonade"
---
# Reactive programming
## So
--
- **reactive programming** = **event-driven programming** the event is "data changed"
--
- **reactive programming** is more declarative
--
- **reactive programming** is not specific to Shiny (e.g. https://quarto.org/docs/computations/ojs.html)
---
# Reactive programming
```{R, non_react}
a <- 2
b <- 2 * a
cat("a =", a, " | ", "b =", b)
```
--
Would `b` change if `a` changes?
--
```{R}
a <- 3
cat("a =", a, " | ", "b =", b)
```
--
Nope!
???
DO NOT BE SHY AND ASK US WHAT IS THAT PIECE OF CODE
---
# Reactive programming
```{R, react1}
# shiny must be installed
library(shiny)
reactiveConsole(TRUE)
```
--
```{R, react2}
a <- reactiveVal(2)
b <- reactive({2 * a()})
cat("a =", a(), " | ", "b =", b())
```
--
Would `b` change if `a` changes?
--
```{R}
a(3)
cat("a =", a(), " | ", "b =", b())
```
--
Yes! Because now variables are somehow linked!
---
# Reactive programming .font80[ `r ar()` building blocks]
.pull-left[
## 1. reactive values
]
.pull-right[
![:scale 26%](img/reactive_graphs/reactVal.png)
]
--
* starting points, no reactivity without them!
* could be any `r rp()` objects
* two ways to initiate them: `reactiveVal()` and `reactiveValues()`
---
# Reactive programming .font80[ `r ar()` building blocks]
.pull-left[
## 1. reactive values
]
.pull-right[
![:scale 26%](img/reactive_graphs/reactVal.png)
]
```{R reactVal1}
a <- reactiveVal(2)
a()
x <- reactiveVal(list(a = 1, mydf = data.frame(a = c(1, 2), b = letters[1:2])))
x()
```
---
# Reactive programming .font80[ `r ar()` building blocks]
.pull-left[
## 1. reactive values
]
.pull-right[
![:scale 26%](img/reactive_graphs/reactVal.png)
]
```{R reactVal2}
a <- reactiveValues(a = 1, mydf = data.frame(a = c(1, 2), b = letters[1:2]))
a
a$a
a$mydf
```
???
no parentheses
---
# Reactive programming .font80[ `r ar()` building blocks]
.pull-left[
## 2. reactive expressions
]
.pull-right[
![:scale 30%](img/reactive_graphs/reactExp.png)
]
* depends on reactive values or other reactive expressions
* can be used in another reactive expression
* special functions (lazy and cached)
* intermediate entities
* can be used to avoid duplication in your reactive code
---
# Reactive programming .font80[ `r ar()` building blocks]
.pull-left[
## 2. reactive expressions
]
.pull-right[
![:scale 30%](img/reactive_graphs/reactExp.png)
]
```{R reactExp2}
a <- reactiveVal(2)
a()
b <- reactive({2*a()})
b()
```
--
```{R reactExp3}
a(4)
b()
```
---
# Reactive programming .font80[ `r ar()` building blocks]
.pull-left[
## 2. reactive expressions
]
.pull-right[
![:scale 30%](img/reactive_graphs/reactExp.png)
]
```{R reactExp4}
a <- reactiveVal(2)
b <- reactive({2 * a()})
a2 <- reactiveVal(runif(1))
# I avoid using `c` as name variable purposely
d <- reactive({
print("executing reactive")
b() + a2()
})
d()
a(3)
d()
```
???
I have to call `d()`, so not automatically!
missing something that would watch change in a or a2!
use runif(1) instead of 2 --> exercice?
---
# Reactive programming .font80[ `r ar()` building blocks]
.pull-left[
## 3. Observers
]
.pull-right[
![:scale 25%](img/reactive_graphs/reactObs.png)
]
* can read reactive values and call reactive expressions
* will automatically re-execute when those dependencies change
* eager (“infectious" eagerness) and forgetful
* the value returned by an observer is ignored
--
<br>
.center[![:scale 32%](img/reactive_graphs/simpleGraph0.png)]
--
.center[![:scale 60%](img/reactive_graphs/simpleGraph.png)]
---
# Reactive programming .font80[ `r ar()` building blocks]
.pull-left[
## 3. Observers
]
.pull-right[
![:scale 25%](img/reactive_graphs/reactObs.png)
]
```{R reactExp5}
observe(d())
a(1)
a(2)
a2(1)
```
???
You won't use observe()
to do in console
---
# Reactive programming .font80[ `r ar()` building blocks]
### 1. Reactive values ~ "*special variables*""
--
### 2. Reactive expressions ~ "*special functions*""
--
### 3. Observers ~ "*special what?*"
???
r <- observe(d())
r$.label
r$.func()
r$.func <- function(){d() + 1}
---
# Exercise
`r lc()` Create a reactive chain that allows you to convert
* Fahrenheit to Celsius
* hints:
- make `temp` your reactive variable that have the temperature in Fahrenheit
- 1`C` = (1`F` - 32) * 5/9 (https://en.wikipedia.org/wiki/Fahrenheit)
--
* feet to meters
--
* Fahrenheit to Celsius and vice-versa
--
* [How to measure things like a Canadian](https://preview.redd.it/k1brffgbngk31.png?width=681&format=png&auto=webp&s=8cc428c345b687a3f79d8e481561781f38d0630e)
`r cdw(minutes = 20, seconds = 0, margin = "1em")`
---
# `r tr()` Special cases
### Special cases that we use all the time to let Shiny do its magic!
--
#### - **`input`**: read-only **reactive values**
--
#### - **`output`**: special **observers**
--
<br>
### **`input`** `r ar()` **`output`**
.center[![:scale 40%](img/reactive_graphs/simpleGraph0.png)]
--
### **`input`** `r ar()` **`reactive expression`** `r ar()` **`output`**
.center[![:scale 70%](img/reactive_graphs/simpleGraph.png)]
---
# Study case
* `r lc()` [Simple shiny app](https://shiny.rstudio.com/gallery/single-file-shiny-app.html)
--
* `r ey()` UI: where the different elements should be
```R
# Define the UI
ui <- bootstrapPage(
numericInput('n', 'Number of obs', n),
plotOutput('plot')
)
```
---
# Study case
* `r cg()` Server: the rules / the reactivity chain(s)
```R
# Define the server code
server <- function(input, output) {
output$plot <- renderPlot({
hist(runif(input$n))
})
}
```
--
* `input$n`: reactive value `n`
* `ouput$plot`: observer `plot`
--
### Reactive graph: **`input$n`** `r ar()` **`output$plot`**
.center[![:scale 40%](img/reactive_graphs/simpleGraph0.png)]
???
Shiny is gonna take care of it for you
---
# Reactive graph
### Reactive graph: **`input$n`** `r ar()` **`output$plot`**
.center[![:scale 40%](img/reactive_graphs/simpleGraph0.png)]
--
### with [`Shiny`](https://CRAN.R-project.org/package=Shiny) we build a **reactive graph** and Shiny takes care of it for us!
--
### In a reactive graph, there are "variables" that depend on each other and this is what enables the interactivity!
---
# Building a shiny app
### Building a more complex graph!
.center[![:scale 75%](img/reactive_graphs/complexGraph.png)]
--
### `r tr()` sometimes you will need to have more control and escape the graph
* `reactiveVal`, `oberveEvent`, `isolate()`, etc.
---
# Let's sum up
1. Shiny allows you to create web applications with `r rp()`
--
2. A shiny app includes a user interface (`ui`) and a server function (`server`)
--
3. A shiny app uses reactive programming to generate outputs based on users inputs
--
4. Shiny takes care of the reactive graph you built: inputs and outputs are presented in `ui`, the rules that link them are defined in `server`
```{R, include = FALSE}
reactiveConsole(FALSE)
```
---
# Let's practice
### `r lc()` Create the reactive graph of this application [Iris k-means clustering](https://shiny.rstudio.com/gallery/kmeans-example.html)
<br>
--
### `r lc()` What's the difference?
.pull-left[
```R
a <- reactiveVal(2)
b <- reactive({2 * a()})
a2 <- reactiveVal(runif(1))
d <- reactive({
print("executing reactive")
b() + a2()
})
observe(d())
```
]
.pull-right[
```R
a <- reactiveVal(2)
b <- reactive({2 * a()})
d <- reactive({
print("executing reactive")
b() + runif(1)
})
observe(d())
```
]
`r cdw(minutes = 15, seconds = 0, margin = "1em")`