-
Notifications
You must be signed in to change notification settings - Fork 0
/
shiny.qmd
1073 lines (828 loc) · 32.6 KB
/
shiny.qmd
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
# Shiny {#sec-shiny}
```{r}
#| eval: true
#| echo: false
#| include: false
source("_common.R")
```
```{r}
#| label: co_box_tldr
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "b",
look = "default", hsize = "1.10", size = "1.05",
header = "![](images/00_index_shiny.png){height=40} TLDR",
fold = TRUE,
contents = "
<br>
A basic **Shiny project** has two files:
An `app.R` and `.Rproj` file:\n
\`\`\`bash
shiny-app/
├── app.R
└── shiny-app.Rproj
\`\`\`
A fully developed **Shiny project** can have the following:
1. An `R/` folder for additional scripts (i.e., modules, helper & utility functions) that is automatically sourced when the application runs\n
    - The only exception to this is a `global.R` file, which is run first\n
2. A `www/` folder for external resources (images, styling, etc.) that is automatically served when the application runs\n
3. An optional `DESCRIPTION` file that controls deployment behaviors (i.e., `DisplayMode`)\n
4. Data files\n
5. An optional `README.md` file for documentation\n
\`\`\`bash
shiny-app/
├── DESCRIPTION
├── R/
│ ├── module.R
│ ├── helper.R
│ └── utils.R
├── README.md
├── app.R
├── data.RData
├── shiny-app.Rproj
└── www/
└── shiny.png
\`\`\`
\\*[Both `R/` and `www/` are automatically loaded when the app launches.]{style='font-style: italic;'}
"
)
```
---
::: {layout="[90, 10]" layout-valign="top"}
This chapter briefly reviews programming with Shiny's reactive model and how it differs from regular R programming. Then, I'll cover some of the unique behaviors of Shiny app projects (and why you might consider adopting them if you haven't already).
![](images/00_index_shiny.png){fig-align="right"}
:::
:::: {.callout-tip collapse='true' appearance='default' icon=false}
## [Accessing applications]{style='font-weight: bold; font-size: 1.15em;'}
::: {style='font-size: 1.05em; color: #282b2d;'}
I've created the [`shinypak` R package](https://mjfrigaard.github.io/shinypak/) In an effort to make each section accessible and easy to follow:
Install `shinypak` using `pak` (or `remotes`):
```{r}
#| code-fold: false
#| message: false
#| warning: false
#| eval: false
# install.packages('pak')
pak::pak('mjfrigaard/shinypak')
```
Review the chapters in each section with `list_apps()`
```{r}
#| code-fold: false
#| message: false
#| warning: false
#| collapse: true
library(shinypak)
list_apps(regex = '^02')
```
Launch the app:
```{r}
#| code-fold: false
#| eval: false
launch(app = "02.3_proj-app")
```
Download the app:
```{r}
#| code-fold: false
#| eval: false
get_app(app = "02.3_proj-app")
```
:::
::::
## Shiny apps {#sec-shiny-projects}
Reactivity is the underlying process that allows Shiny apps to update and respond to user interactions automatically. Developing Shiny apps involves harnessing the connection between inputs, reactivity, and outputs to control and predict the application's behavior.
Shiny programming differs from regular R programming in several key aspects:
- **An Event-driven UI**: Shiny apps require developers to design and develop a user interface (UI). [User experience (UX) design](https://bootcamp.cvn.columbia.edu/blog/what-is-ux-design/#:~:text) is an entirely separate field, but as Shiny developers, we need to know enough to allow users to interact with and navigate our apps. The UI also captures each ‘event,’ meaning that the user’s actions (such as button clicks or input changes) trigger the application's inputs, updates, or outputs.
- Regular R programming often involves executing predefined steps or functions without direct interaction or responses to user events.
- **A Reactive Server**: In Shiny, the application’s behavior is determined by the dependencies between reactive inputs (i.e., the `inputId`s), reactive values, and outputs (i.e., the `outputId`s), allowing for automatic updates and propagation of changes throughout the application.
- In standard R programming, we typically define a series of sequential steps (i.e., functions) that operate on data to generate output to the console or a typesetting system for technical and scientific publications (model results, graphs, tables, etc.) without accounting for reactivity or downstream changes.
Learning reactivity can be challenging when you start, but fortunately, there are [excellent tutorials](https://shiny.posit.co/r/getstarted/shiny-basics/lesson1/index.html) and [articles](https://shiny.posit.co/r/articles/build/understanding-reactivity/) to help you along the way!
```{r}
#| label: git_box_moviesApp_main
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = 'launch',
fig_pw = '75%',
branch = "02.1_shiny-app",
repo = 'sap')
```
If you're creating a new application using the **New Project Wizard**, you'll see the following:
::: {#fig-shiny_new_project_wizard}
![New Shiny app](images/shiny_new_project_wizard.png){#fig-shiny_new_project_wizard width="75%" fig-align="center"}
New Shiny app project
:::
Select the location of your Shiny app project, then pick a name and decide whether you want to use Git or `renv` (I'll be using Git).
::: {#fig-shiny_new_shiny_proj}
![Shiny app info](images/shiny_new_shiny_proj.png){#fig-shiny_new_shiny_proj width="75%" fig-align="center"}
New Shiny app project in a Git repository
:::
After clicking **Create Project**, a new session will open with your project files.
Note that the only items in the new Shiny app project are `app.R` and the `sap.Rproj` file.
```{bash}
#| eval: false
#| code-fold: false
sap/
├── app.R
└── sap.Rproj
1 directory, 2 files
```
### Boilerplate [`app.R`]{style='font-size: 1.05em;'} {#sec-boilerplate-app-dot-r}
`app.R` initially contains a boilerplate application, which we can launch by clicking on the **Run App** button:
::: {.column-margin}
![Click on **Run App**](images/shiny_run_app.png){width="75%" fig-align="center"}
:::
::: {#fig-shiny_old_faithful}
![Old Faithful geyser app](images/shiny_old_faithful.png){#fig-shiny_old_faithful width="100%" fig-align="center"}
Boilerplate Old Faithful geyser app in new Shiny projects
:::
The boilerplate 'Old Faith Geyser Data' app is a perfect example of what Shiny can do with a single `app.R` file, but we'll want to exchange this code for a *slightly* more advanced application (because most Shiny apps grow beyond an `app.R` file).
## Movie review data app {#sec-introduce-movie-review-app}
Most Shiny applications move beyond a single `app.R` file. Knowing how to store any utility functions, data, documentation, and metadata will set you up for success as you transition to storing your app in an R package.
```{r}
#| label: git_launch_02.2_movies-app
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = "launch",
branch = "02.2_movies-app")
```
I'm going to work through an example of some intermediate/advanced Shiny app features using the application from the [Building Web Applications with Shiny](https://rstudio-education.github.io/shiny-course/) course. This app is a great use case for the following reasons:
1. It has **multiple input types** that are collected in the UI
2. The graph output can be converted to a **utility function**
3. The app loads an **external data** file when it's launched
4. The code is accessible (and comes from a trusted source)
### App
The code below replaces the boilerplate 'Old Faith Geyser Data' app in `app.R`:
#### `app.R` {#sec-initial-movie-review-app-dot-r}
```{r}
#| code-fold: show
#| eval: false
#| code-summary: 'show/hide movie review Shiny app'
ui <- shiny::fluidPage(
theme = shinythemes::shinytheme("spacelab"),
shiny::sidebarLayout(
shiny::sidebarPanel(
shiny::selectInput(
inputId = "y",
label = "Y-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "audience_score"
),
shiny::selectInput(
inputId = "x",
label = "X-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "critics_score"
),
shiny::selectInput(
inputId = "z",
label = "Color by:",
choices = c(
"Title Type" = "title_type",
"Genre" = "genre",
"MPAA Rating" = "mpaa_rating",
"Critics Rating" = "critics_rating",
"Audience Rating" = "audience_rating"
),
selected = "mpaa_rating"
),
shiny::sliderInput(
inputId = "alpha",
label = "Alpha:",
min = 0, max = 1,
value = 0.4
),
shiny::sliderInput(
inputId = "size",
label = "Size:",
min = 0, max = 5,
value = 3
),
shiny::textInput(
inputId = "plot_title",
label = "Plot title",
placeholder = "Enter text to be used as plot title"
),
shiny::actionButton(
inputId = "update_plot_title",
label = "Update plot title"
)
),
shiny::mainPanel(
shiny::br(),
shiny::p(
"These data were obtained from",
shiny::a("IMBD", href = "http://www.imbd.com/"), "and",
shiny::a("Rotten Tomatoes", href = "https://www.rottentomatoes.com/"), "."
),
shiny::p(
"The data represent",
nrow(movies),
"randomly sampled movies released between 1972 to 2014 in the United States."
),
shiny::plotOutput(outputId = "scatterplot"),
shiny::hr(),
shiny::p(shiny::em(
"The code for this Shiny application comes from",
shiny::a("Building Web Applications with shiny",
href = "https://rstudio-education.github.io/shiny-course/"
)
))
)
)
)
server <- function(input, output, session) {
new_plot_title <- shiny::reactive({
tools::toTitleCase(input$plot_title)
}) |>
shiny::bindEvent(input$update_plot_title,
ignoreNULL = FALSE,
ignoreInit = FALSE
)
output$scatterplot <- shiny::renderPlot({
scatter_plot(
df = movies,
x_var = input$x,
y_var = input$y,
col_var = input$z,
alpha_var = input$alpha,
size_var = input$size
) +
ggplot2::labs(title = new_plot_title()) +
ggplot2::theme_minimal() +
ggplot2::theme(legend.position = "bottom")
})
}
shiny::shinyApp(ui = ui, server = server)
```
### Additional files
I've added the `scatter_plot()` utility function in a new `utils.R` file:
#### `utils.R` {#sec-initial-movie-review-utils}
```{r}
#| code-fold: show
#| eval: false
#| code-summary: 'show/hide scatter_plot()'
scatter_plot <- function(df, x_var, y_var, col_var, alpha_var, size_var) {
ggplot2::ggplot(data = df,
ggplot2::aes(x = .data[[x_var]],
y = .data[[y_var]],
color = .data[[col_var]])) +
ggplot2::geom_point(alpha = alpha_var, size = size_var)
}
```
#### `movies.RData` {#sec-initial-movie-review-data}
The `movies.RData` dataset contains reviews from [IMDB](https://www.imdb.com/) and [Rotten Tomatoes](https://www.rottentomatoes.com/)
You can download these data [here](https://github.com/mjfrigaard/bbsa/raw/main/movies.RData)
### Updated movies app project contents
The `sap` project now contains the following files:
```{bash}
#| eval: false
#| code-fold: false
sap/
├── app.R
├── movies.RData
├── sap.Rproj
└── utils.R
2 directories, 4 files
```
To run the `movies` app, we need to load the data and source the `utils.R` file by adding the code below to the top of the `app.R` file:
*After installing the packages below, add a comment (`#`) in front of these lines.*
I've placed the header below in the top of the `app.R` file:
```{r}
#| eval: false
#| code-fold: false
# install ------------------------------------
# after installing, comment this out
pkgs <- c("shiny", "shinythemes", "stringr", "ggplot2", "rlang") # <1>
install.packages(pkgs, verbose = FALSE) # <1>
# <1>
# packages ------------------------------------
library(shiny)
library(shinythemes)
library(stringr)
library(ggplot2)
library(rlang)
# data -----------------------------------------
load("movies.RData")
# utils ----------------------------------------
source("utils.R")
```
1. Comment out these lines after installing `pkgs`
Clicking on **Run App** displays the movie review app:
:::: {.column-page-inset-right}
::: {#fig-shiny_movies_app}
![`movies` app](images/shiny_movies_app.png){#fig-shiny_movies_app width="100%" fig-align="center"}
Movie review app
:::
::::
## Project folders {#sec-shiny-folders}
Now that we have a *slightly* more complex application in `app.R`, I’ll add a few project folders we can include in our project that have unique built-in behaviors. These folders will help organize your files and make additional resources available to your app.
```{r}
#| label: git_launch_03_proj-app
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = "launch",
branch = "02.3_proj-app")
```
### [`R/`]{style='font-size: 1.05em;'}
If your Shiny app relies on utility or helper functions (outside the `app.R` file), you can place this code in an `R/` folder. Any `.R` files in the `R/` folder will be automatically sourced when the application is run.
::: {.callout-note title="Place `utils.R` in `R/` folder" collapse='true' appearance='simple'}
I've moved the `utils.R` file into the `R/` folder in `sap`:
```{bash}
#| eval: false
#| code-fold: false
sap/
└── R/
└── utils.R
1 directory, 1 file
```
:::
The function that makes this process (i.e., sourcing any `.R` files in an `R/` folder) possible is [`loadSupport()`](https://shiny.posit.co/r/reference/shiny/1.5.0/loadsupport). We'll return to this function in a later chapter, because the `R/` folder has a similar behavior (but different function) in R packages.[^load-support-1]
[^load-support-1]: Shiny introduced these features in version 1.3.2.9001, and you can read more about them in the section titled, '*The `R/` directory*' in [App formats and launching apps](https://shiny.posit.co/r/articles/build/app-formats/)
### [`www/`]{style='font-size: 1.05em;'}
When you run a Shiny application, any static files (i.e., resources) under a `www/` directory will automatically be made available within the application. This folder stores images, CSS or JavaScript files, and other static resources.
::: {.callout-note title="Create `www/` folder and download image" collapse='true' appearance='simple'}
I've downloaded the Shiny logo ([`shiny.png`](https://raw.githubusercontent.com/rstudio/hex-stickers/main/PNG/shiny.png)) and stored it in the `www/` folder.
```{bash}
#| eval: false
#| code-fold: false
sap/
└── www/
└── shiny.png
1 directory, 1 file
```
In the section below, we'll reference `shiny.png` directly in the UI.
:::
Following the conventional folder structure will also help set you up for success when/if you decide to convert it into an app-package.
## Project files {#sec-shiny-files}
### [`README.md`]{style='font-size: 1.10em;'}
Including a `README.md` file in your root folder is a good practice for any project. `README.md` should contain relevant documentation for running `app.R`.
::: {.callout-note title="Create `README.md`" collapse='true' appearance='simple'}
I've included the content below in the `README.md` file
```Markdown
# movies app
The original code and data for this Shiny app comes from the [Building Web Applications with Shiny](https://rstudio-education.github.io/shiny-course/) course. It's been converted to use [shiny modules](https://shiny.posit.co/r/articles/improve/modules/).
View the code for this application in the [`sap` branches](https://github.com/mjfrigaard/sap/branches/all).
```
:::
### [`DESCRIPTION`]{style='font-size: 1.05em;'}
`DESCRIPTION` files play an essential role in R packages, but they are also helpful in Shiny projects if I want to deploy the app in [showcase mode](https://shiny.posit.co/r/articles/build/display-modes/).
::: {.callout-note title="Create `DESCRIPTION`" collapse='true' appearance='simple'}
I've included the content below in `DESCRIPTION`:
```{bash}
#| eval: false
#| code-fold: false
Type: shiny
Title: movies app
Author: John Smith
DisplayMode: Showcase
```
:::
::::{.column-margin}
:::{style="font-weight: bold; font-size: 1.10em"}
*It's always a good idea to leave at least one `<empty final line>` in your `DESCRIPTION` file.*
:::
::::
After adding `README.md` and a `DESCRIPTION` file (listing `DisplayMode: Showcase`), the movies app will display the code and documentation when the app launches.[^showcase-mode]
[^showcase-mode]: Read more about `showcase` mode [here](https://shiny.posit.co/r/articles/build/display-modes/)
## Project code {#sec-shiny-code-files}
The following two items are considered best practices because they make your app more scalable by converting `app.R` into functions.
### Modules {#sec-shiny-modules}
Shiny modules are a '[pair of UI and server functions](https://mastering-shiny.org/scaling-modules.html)' designed to compartmentalize input and output IDs into distinct namespaces,
> *'...a namespace is to an ID as a directory is to a file...'* - [`shiny::NS()` help file](https://shiny.posit.co/r/reference/shiny/latest/ns).
Module UI functions typically wrap the layout, input, and output functions in `shiny::tagList()`. Module server functions typically contain the ‘backend’ code in a Shiny server function. Both the UI and server module functions are linked by an `id` argument, which is created using `shiny::NS()` (namespace) in the UI function and called in the server function with `shiny::moduleServer()`.
#### Variable inputs module
`mod_var_input_ui()` creates a dedicated namespace for the `inputId`s with `shiny::NS()`:
##### [`R/mod_var_input.R`]{style='font-size: 0.90em:'}
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide mod_var_input_ui()'
mod_var_input_ui <- function(id) {
ns <- shiny::NS(id)
shiny::tagList(
shiny::selectInput(
inputId = ns("y"), # <1>
label = "Y-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "audience_score"
),
shiny::selectInput(
inputId = ns("x"), # <2>
label = "X-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "imdb_rating"
),
shiny::selectInput(
inputId = ns("z"), # <3>
label = "Color by:",
choices = c(
"Title Type" = "title_type",
"Genre" = "genre",
"MPAA Rating" = "mpaa_rating",
"Critics Rating" = "critics_rating",
"Audience Rating" = "audience_rating"
),
selected = "mpaa_rating"
),
shiny::sliderInput(
inputId = ns("alpha"), # <4>
label = "Alpha:",
min = 0, max = 1, step = 0.1,
value = 0.5
),
shiny::sliderInput(
inputId = ns("size"), # <5>
label = "Size:",
min = 0, max = 5,
value = 2
),
shiny::textInput(
inputId = ns("plot_title"), # <6>
label = "Plot title",
placeholder = "Enter plot title"
)
)
}
```
1. `y` axis numeric variable
2. `x` axis numeric variable
3. `z` axis categorical variable
4. `alpha` numeric value for points
5. `size` numeric value for size
6. `plot_title` text
`mod_var_input_server()` returns these values in a reactive list with `shiny::reactive()`:
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide mod_var_input_server()'
mod_var_input_server <- function(id) {
shiny::moduleServer(id, function(input, output, session) {
return(
reactive({
list(
"y" = input$y, # <1>
"x" = input$x, # <2>
"z" = input$z, # <3>
"alpha" = input$alpha, # <4>
"size" = input$size, # <5>
"plot_title" = input$plot_title # <6>
)
})
)
})
}
```
1. `y` axis numeric variable
2. `x` axis numeric variable
3. `z` axis categorical variable
4. `alpha` numeric value for points
5. `size` numeric value for size
6. `plot_title` text
#### Scatter-plot display module
`mod_scatter_display_ui()` creates a dedicated namespace for the plot `outputId` (as `"scatterplot"`), along with some help text:
##### [`R/mod_scatter_display.R`]{style='font-size: 0.90em:'}
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide mod_scatter_display_ui()'
mod_scatter_display_ui <- function(id) {
ns <- shiny::NS(id)
shiny::tagList(
shiny::tags$br(),
shiny::tags$blockquote(
shiny::tags$em(
shiny::tags$h6("The data for this application comes from the ",
shiny::tags$a("Building web applications with Shiny",
href = "https://rstudio-education.github.io/shiny-course/"),
"tutorial"))
),
shiny::plotOutput(outputId = ns("scatterplot")) # <1>
)
}
```
1. Namespaced module `id` for plot in UI
The code to render the `output$scatterplot` is contained in the nested call to `shiny::moduleServer()` in `mod_scatter_display_server()`:
After 1) loading the `movies` data, 2) assembling the returned values from `mod_var_input_server()`, and creating the `input()` reactive, 3) the `scatter_plot()` utility function creates the `plot` object and adds the `plot_title()` and theme:
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide mod_scatter_display_server()'
mod_scatter_display_server <- function(id, var_inputs) {
shiny::moduleServer(id, function(input, output, session) {
load("movies.RData") # <1>
inputs <- shiny::reactive({ # <2>
plot_title <- tools::toTitleCase(var_inputs()$plot_title) # <2>
list( # <2>
x = var_inputs()$x, # <2>
y = var_inputs()$y, # <2>
z = var_inputs()$z, # <2>
alpha = var_inputs()$alpha, # <2>
size = var_inputs()$size, # <2>
plot_title = plot_title # <2>
) # <2>
}) # <2>
output$scatterplot <- shiny::renderPlot({ # <3>
plot <- scatter_plot( # <3>
df = movies, # <3>
x_var = inputs()$x, # <3>
y_var = inputs()$y, # <3>
col_var = inputs()$z, # <3>
alpha_var = inputs()$alpha, # <3>
size_var = inputs()$size # <3>
) # <3>
plot + # <4>
ggplot2::labs( # <4>
title = inputs()$plot_title, # <4>
x = stringr::str_replace_all( # <4>
tools::toTitleCase( # <4>
inputs()$x), # <4>
"_", " "), # <4>
y = stringr::str_replace_all( # <4>
tools::toTitleCase( # <4>
inputs()$y), # <4>
"_", " ") # <4>
) +
ggplot2::theme_minimal() + # <5>
ggplot2::theme(legend.position = "bottom") # <5>
})
})
}
```
1. loading the `movies` data
2. assembling the returned values from `mod_var_input_server()`, and creating the `input()` reactive
3. `scatter_plot()` utility function creates the `plot` object
4. adds the `plot_title()`
5. add `theme` to layers
Both UI and server module functions are combined into a single `.R` file, and all modules are placed in the `R/` folder so they are sourced when the application is run.
```{bash}
#| eval: false
#| code-fold: false
R/
├── mod_scatter_display.R
├── mod_var_input.R
└── utils.R
```
### Standalone app function {#sec-shiny-standalone-app-fun}
Both module functions are combined in the `ui` and `server` arguments of `shiny::shinyApp()`. The `id` arguments (`"vars"` and `"plot"`) connect the UI functions to their server counterparts, and the output from `mod_var_input_server()` is the `var_inputs` argument in `mod_scatter_display_server()`.
The call to `shiny::shinyApp()` is wrapped in the `launch_app()` function and placed in `app.R`.
##### `app.R`
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide launch_app() in app.R'
# install ------------------------------------
# after installing, comment this out
pkgs <- c("shiny", "shinythemes", "stringr", "ggplot2", "rlang") # <1>
install.packages(pkgs, verbose = FALSE) # <1>
# packages ------------------------------------
library(shiny) # <2>
library(shinythemes) # <2>
library(stringr) # <2>
library(ggplot2) # <2>
library(rlang) # <2>
launch_app <- function() {
shiny::shinyApp(
ui = shiny::fluidPage(
shiny::titlePanel(
shiny::div(
shiny::img(
src = "shiny.png",
height = 60,
width = 55,
style = "margin:10px 10px"
),
"Movies Reviews"
)
),
shiny::sidebarLayout(
shiny::sidebarPanel(
mod_var_input_ui("vars") # <3>
),
shiny::mainPanel(
mod_scatter_display_ui("plot") # <4>
)
)
),
server = function(input, output, session) {
selected_vars <- mod_var_input_server("vars") # <5>
mod_scatter_display_server("plot", var_inputs = selected_vars) # <6>
}
)
}
launch_app()
```
1. Header (comment this out after the packages are installed)
2. Load packages
3. Variable input UI module
4. Graph display UI module
5. Variable input server module
6. Graph display server module
Now, I can run the app with `launch_app()`.
:::: {.column-page-inset-right}
::: {#fig-shiny_proj_movies_app}
![Movie reviews app](images/shiny_proj_movies_app.png){#fig-shiny_proj_movies_app width="100%" fig-align="center"}
View a deployed version [here](https://mjfrigaard.shinyapps.io/moviesApp/).
:::
::::
The deployed files of `sap` are below:
```{bash}
#| eval: false
#| code-fold: false
sap/ # 02.3_proj-app branch
├── DESCRIPTION
├── R/
│ ├── mod_scatter_display.R
│ ├── mod_var_input.R
│ └── utils.R
├── README.md
├── app.R
├── movies.RData
├── sap.Rproj
├── rsconnect/
│ └── shinyapps.io/
│ └── user/
│ └── sap.dcf
└── www/
└── shiny.png
6 directories, 10 files
```
:::{.column-margin}
The `rsconnect/` folder has been removed from the [`02.3_proj-app`](https://github.com/mjfrigaard/sap/tree/02.3_proj-app) branch.
:::
## Additional features {#sec-adv-shiny-projects}
Below are two additional 'optional' features that *can* be included with your Shiny application (I consider these 'optional' because they're use depends on the specific needs and environment for each application).
### Global variables and/or functions
Placing a `global.R` file in your root folder (or in the `R/` directory) causes this file to be sourced only once when the Shiny app launches, rather than each time a new user connects to the app. `global.R` is commonly used for initializing variables, loading libraries, loading large data sets and/or performing initial calculations.
::: {.callout-note title="Using `global.R`" collapse='true' appearance='simple'}
I *could* place the header from `app.R` in `global.R` to ensure these packages are loaded before the application launches:
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide contents of R/global.R'
# packages ------------------------------------
library(shiny)
library(shinythemes)
library(stringr)
library(ggplot2)
library(rlang)
```
`global.R` can be placed in the `R/` folder
```
R/
├── global.R
├── mod_scatter_display.R
├── mod_var_input.R
└── utils.R
1 directory, 4 files
```
Or in the project root folder
```
├── DESCRIPTION
├── R
│ ├── mod_scatter_display.R
│ ├── mod_var_input.R
│ └── utils.R
├── README.md
├── app.R
├── global.R
├── man
├── movies.RData
├── sap.Rproj
└── www
└── shiny.png
4 directories, 10 files
```
In both locations, it will be sourced before launching the application.
:::
`global.R` can be used to maintain efficiency and consistency across application sessions.
### Project dependencies with [`renv`]{style='font-size: 1.05em;'}
If you use [`renv`](https://rstudio.github.io/renv/articles/renv.html), keep track of your dependencies by regularly running `renv::status()` and `renv::snapshot()`.
::: {.callout-note title="Using `renv`" collapse='true' appearance='simple'}
Start by initiating `renv` with `renv::init()`, then run `renv::status()` to check which packages have been added to the lockfile:
```{r}
#| eval: false
#| code-fold: false
renv::status()
```
``` sh
The following package(s) are in an inconsistent state:
package installed recorded used
colorspace y n y
fansi y n y
farver y n y
ggplot2 y n y
gtable y n y
isoband y n y
labeling y n y
lattice y n y
MASS y n y
Matrix y n y
mgcv y n y
munsell y n y
nlme y n y
pillar y n y
pkgconfig y n y
RColorBrewer y n y
scales y n y
shinythemes y n y
tibble y n y
utf8 y n y
vctrs y n y
viridisLite y n y
```
Take a 'snapshot' to capture the current package dependencies:
```{r}
#| eval: false
#| code-fold: false
renv::snapshot()
```
``` sh
The following package(s) will be updated in the lockfile: