-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreactivity.qmd
1960 lines (1469 loc) · 56.1 KB
/
reactivity.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
# Reactivity essentials
### Diving deeper into reactive programming
```{r setup, include=FALSE}
library(shiny)
library(tidyverse)
library(rsconnect)
knitr::opts_chunk$set(
echo = FALSE,
fig.align = "center",
out.width = "80%"
)
```
## 3.1 Reactive elements
### Reactive objects
In this section we discuss reactivity in a bit more detail.
Three components of reactive execution in Shiny are
- reactive inputs,
- reactive expressions, and
- reactive outputs.
We're going to denote them with these symbols:
```{r image-input-expression-output, out.width = "60%"}
knitr::include_graphics("images/input-expression-output.png")
```
### Reactive inputs and outputs
```{r image-input-output, out.width = "40%"}
knitr::include_graphics("images/input-output.png")
```
- A **reactive input** is a user input that comes through a browser interface, typically.
- A **reactive output** is something that appears in the user's browser window, such as a plot or a table of values.
- One reactive input can be connected to multiple outputs, and vice versa. For example we might have a UI input widget for filtering out data based on user's selection, and the filtered data can be used in multiple outputs like plots and summaries.
### Reactive expressions
A **reactive expressions** is component between an input and an output.\
It can both be a dependent (i.e be a child) and have dependents (i.e. be a parent).
```{r image-input-expression-outputs, out.width = "40%"}
knitr::include_graphics("images/input-expression-outputs.png")
```
### Practice
Which of the following is false?
#``{r mc-1, echo=FALSE}
#question("Which of the following is false? Select all that apply.",
# answer("Reactive inputs can only be parents."),
# answer("Reactive inputs can only be children.", correct = TRUE),
# answer("Reactive expressions can be parents."),
# answer("Reactive expressions can be children."),
# answer("Reactive outputs can be parents.", correct = TRUE),
# answer("Reactive outputs can be children"),
# allow_retry = TRUE
#)
#```
###
To illustrate reactivity we're going to start with this app once again
```{r image-app-selectinput-scatterplot}
knitr::include_graphics("images/app-selectinput-scatterplot.png")
```
###
And end up with an app that...
- lets the user subset the data by movie type
- updates the plot for those selected movie types
- and display some text noting the number of movies in the selection
```{r image-app-scatterplot-text}
knitr::include_graphics("images/app-scatterplot-text.png")
```
The subsetted movies data frame gets used in two places, plot and text outputs. Hence, we we're going to make use of reactive expressions to build this app.
### 1. **ui:** Add a UI element for the user to select which movie type(s) of moves they want to plot with `selectInput()`.
```{r image-input, out.width = "10%", fig.align = "left"}
knitr::include_graphics("images/input.png")
```
```{r snippet-selectInput, eval = FALSE, echo = TRUE}
# Select which types of movies to plot
selectInput(
inputId = "selected_type",
label = "Select movie type:",
choices = levels(movies$title_type),
selected = "Feature Film"
)
```
- We define an `inputId()` that we'll use to refer to the input element to later in the app
- We come up with a user facing `label`
- We specify the choices users can select from,
- as well as a default choice
### 2. **server:** Filter for chosen title type and save the new data frame as a reactive expression.
Next, we filter for selected title type and save the new data frame as a reactive expression using the `reactive()` function.
```{r image-expression, out.width = "10%", fig.align = "left"}
knitr::include_graphics("images/expression.png")
```
```{r snippet-movies_subset, echo = TRUE, eval = FALSE}
# Create a subset of data filtering for chosen title types
movies_subset <- reactive({
req(input$selected_type)
filter(movies, title_type %in% input$selected_type)
})
```
This function creates a **cached expression** that knows it is out of date when its input changes. So you, the Shiny developer, do not need to worry about keeping track of when the input changes, Shiny automatically does that for you.
Two more things to note here:
1. Before we do any calculations that depends on `input$selected_type`, we check its availability with the `req()` function, and
2. We surround the expression with curly braces
### 3. **server:** Use `movies_subset` (which is reactive) for plotting.
The next two steps could happen in either order. Let's start with the plot first.
```{r image-output-1, out.width = "10%", fig.align = "left"}
knitr::include_graphics("images/output.png")
```
```{r snippet-scatterplot, echo = TRUE, eval = FALSE}
# Create scatterplot
output$scatterplot <- renderPlot({
ggplot(data = movies_subset(),aes_string(x = input$x, y = input$y)) +
geom_point()
})
```
You should be familiar with creating plots using the `renderPlot()` function by now. But there is something new here. The data frame we're using is no longer movies, but the new reactive expression we created. And because it's reactive we refer to it with parentheses after its name. This is, once again, a cached expression, meaning that it will only rerun when its inputs change.
### 3. **ui** & **server:** Use movies_subset (which is reactive) for printing number of observations.
```{r image-output-2, out.width = "10%", fig.align = "left"}
knitr::include_graphics("images/output.png")
```
And lastly we create the text stating the number of observations in the selection. The obvious choice for creating this output would be `renderText()`. But I feel like getting a little fancier with this one. Suppose we know a bit of HTML -- which is true, I really only know a bit of HTML -- and I want to use some text decoration, like bolding and line breaks in my text output. So we need a rendering function that generates HTML, which is `renderUI()`.
```{r snippet-uiOutput, echo = TRUE, eval = FALSE}
# ui - Lay out where text should appear on app
mainPanel(
...
# Print number of obs plotted
uiOutput(outputId = "n"),
...
)
```
```{r snippet-renderUI, echo = TRUE, eval = FALSE}
# server - Print number of movies plotted
output$n <- renderUI({
HTML(paste0(
"The plot displays the relationship between the <br>
audience and critics' scores of <br>",
nrow(movies_subset()),
" <b>", input$selected_type, "</b> movies."
))
})
```
We use the `paste()` function to string along the text of the sentence we want displayed on the app. This sentence depends on the value of the number of rows of the `movies_subset` reactive expression we created earlier, as well as `input$selected` type.
Using simple HTML we add some decoration to the text, and finally wrap the whole thing up in a function that marks the given text as HTML.
Then on the ui side, we use the counterpart `uiOutput()` function to lay out the text on the app.
### Practice - Add reactive data frame
We ended the previous chapter with an app that allows you to download a data file with selected variables from the `movies` dataset. We will now extend this app by adding a table output of the selected data as well. Given that the same dataset will be used in two outputs, it makes sense to make our code more efficient by using a reactive data frame.
Extend app by adding reactive data frame, which is a subset, that is used in the plot.
#### Your turn
- Define `movies_selected`: a reactive data frame consisting of selected variables (`input$selected_var`).
- Use the newly constructed `movies_selected` reactive data frame to avoid reconstructing the subsetted data frame multiple times throughout the app.
::: proj
*Complete the exercise by navigating to the RStudio Cloud Project titled **3-1 Add reactive data frame** in your RStudio Workspace*
[<i class="fa fa-cloud"></i> Go to RStudio Cloud Project](https://rstudio.cloud/spaces/81721/join?access_code=I4VJaNsKfTqR3Td9hLP7E1nz8%2FtMg6Xbw9Bgqumv){.btn .test-drive}
:::
```{r ex-3-1-reactive, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(dplyr)
library(readr)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
radioButtons(
inputId = "filetype",
label = "Select filetype:",
choices = c("csv", "tsv"),
selected = "csv"
),
checkboxGroupInput(
inputId = "selected_var",
label = "Select variables:",
choices = names(movies),
selected = c("title")
)
),
mainPanel(
dataTableOutput(outputId = "moviestable"),
downloadButton("download_data", "Download data")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
# Create reactive data frame
movies_selected <- ___
# Create data table
output$moviestable <- DT::renderDataTable({
req(input$selected_var)
datatable(
data = movies %>% select(input$selected_var),
options = list(pageLength = 10),
rownames = FALSE
)
})
# Download file
output$download_data <- downloadHandler(
filename = function() {
paste0("movies.", input$filetype)
},
content = function(file) {
if (input$filetype == "csv") {
write_csv(movies %>% select(input$selected_var), file)
}
if (input$filetype == "tsv") {
write_tsv(movies %>% select(input$selected_var), file)
}
}
)
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)
```
<details>
<summary>
Show solution
</summary>
See the following code chunk for the solution to the exercise above.
```{r ex-3-1-reactive-solution, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(dplyr)
library(readr)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
radioButtons(
inputId = "filetype",
label = "Select filetype:",
choices = c("csv", "tsv"),
selected = "csv"
),
checkboxGroupInput(
inputId = "selected_var",
label = "Select variables:",
choices = names(movies),
selected = c("title")
)
),
mainPanel(
dataTableOutput(outputId = "moviestable"),
downloadButton("download_data", "Download data")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
# Create reactive data frame
movies_selected <- reactive({
movies %>% select(input$selected_var)
})
# Create data table
output$moviestable <- DT::renderDataTable({
req(input$selected_var)
datatable(
data = movies_selected(),
options = list(pageLength = 10),
rownames = FALSE
)
})
# Download file
output$download_data <- downloadHandler(
filename = function() {
paste0("movies.", input$filetype)
},
content = function(file) {
if (input$filetype == "csv") {
write_csv(movies_selected(), file)
}
if (input$filetype == "tsv") {
write_tsv(movies_selected(), file)
}
}
)
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
### Practice: Identify reactive objects
The `movies_selected()` reactive expression from the previous exercise is a...
#```{r mc-2, echo=FALSE}
#question("The `movies_selected()` reactive expression from the previous exercise is a...",
# answer("Reactive input"),
# answer("Reactive expression", correct = TRUE),
# answer("Reactive output"),
# answer("Reactive paradigm"),
# allow_retry = TRUE,
# try_again = "Try again -- does it have children? Does it have parents? Does it have both?"
#)
#```
## 3.2 Using reactives
In this section we discuss why we use reactives.
### Why use reactives?
In the previous exercises we were able to reuse our subsetted data frame in multiple places in the server after defining it once as a reactive expression.
In general, reactive expressions help you avoid copy-and-paste code and let you not repeat yourself, and they also help decompose large and complex calculations into smaller pieces.
These benefits are similar to what happens when you decompose a large complex R script into a series of small functions that build on each other
### Functions vs. reactives
While functions and reactives help accomplish similar goals in terms of not-repeating oneself, they're different in implementation.
- Each time you call a function, R will evaluate it.
- However reactive expressions are lazy, they only get executed when their input changes. This means that even if you call a reactive expression multiple times in your app, it will only re-execute when its inputs change.
### Reactlog
Using many reactive expressions in your app can create a complicated dependency structure in your app.
The **reactlog** is a graphical representation of this dependency structure, and it also gives you very detailed information about what's happening under the hood as Shiny evaluates your application.
To view the reactlog:
- Start a fresh R session, and run `options(shiny.reactlog = TRUE)`
- Then launch your app as you normally would
- and in the app press `Ctrl + F3` (or on a Mac: `Cmd + F3`).
###
The reactlog for the app we developed in the previous section looks like this. It uses the icons for reactive inputs, expressions, and outputs that we saw earlier in the course.
```{r image-reactlog}
knitr::include_graphics("images/reactlog.png")
```
- Outputs are at the end of the reactive flow.
- Inputs are at the beginning.\
- `movies_subset()` is a reactive expression in between the input and the outputs.
This visualization also makes it easy to view the inputs the reactive expression depends on and the output that depend on it.
### Practice - Find missing reactives
In the following app code there are a number of spots where reactives are not used properly.
#### Your turn
Debug the app, making sure reactives are being used correctly.
::: proj
*Complete the exercise by navigating to the RStudio Cloud Project titled **3-2a Find missing reactives** in your RStudio Workspace*
[<i class="fa fa-cloud"></i> Go to RStudio Cloud Project](https://rstudio.cloud/spaces/81721/join?access_code=I4VJaNsKfTqR3Td9hLP7E1nz8%2FtMg6Xbw9Bgqumv){.btn .test-drive}
:::
```{r ex-3-2a-debug-reactives, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
library(dplyr)
library(tools)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
titlePanel("Movie browser"),
sidebarLayout(
sidebarPanel(
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"
),
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"
),
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"
),
textInput(
inputId = "plot_title",
label = "Plot title",
placeholder = "Enter text for plot title"
),
checkboxGroupInput(
inputId = "selected_type",
label = "Select movie type(s):",
choices = c("Documentary", "Feature Film", "TV Movie"),
selected = "Feature Film"
)
),
mainPanel(
plotOutput(outputId = "scatterplot"),
textOutput(outputId = "description")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
# Create a subset of data filtering for selected title types
movies_subset <- reactive({
req(input$selected_type)
filter(movies, title_type %in% input$selected_type)
})
# Convert plot_title toTitleCase
output$pretty_plot_title <- toTitleCase(input$plot_title)
# Create scatterplot object the plotOutput function is expecting
output$scatterplot <- renderPlot({
ggplot(
data = movies_subset,
aes_string(x = input$x, y = input$y, color = input$z)
) +
geom_point() +
labs(title = pretty_plot_title)
})
# Create descriptive text
output$description <- renderText({
paste0("The plot above titled '", pretty_plot_title, "' visualizes the relationship between ", input$x, " and ", input$y, ", conditional on ", input$z, ".")
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)
```
<details>
<summary>
Show solution
</summary>
See the following code chunk for the solution to the exercise above.
```{r ex-3-2a-debug-reactives-solution, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
library(dplyr)
library(tools)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
titlePanel("Movie browser"),
sidebarLayout(
sidebarPanel(
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"
),
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"
),
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"
),
textInput(
inputId = "plot_title",
label = "Plot title",
placeholder = "Enter text for plot title"
),
checkboxGroupInput(
inputId = "selected_type",
label = "Select movie type(s):",
choices = c("Documentary", "Feature Film", "TV Movie"),
selected = "Feature Film"
)
),
mainPanel(
plotOutput(outputId = "scatterplot"),
textOutput(outputId = "description")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
# Create a subset of data filtering for selected title types
movies_subset <- reactive({
req(input$selected_type)
filter(movies, title_type %in% input$selected_type)
})
# Convert plot_title toTitleCase
pretty_plot_title <- reactive({
toTitleCase(input$plot_title)
})
# Create scatterplot object the plotOutput function is expecting
output$scatterplot <- renderPlot({
ggplot(
data = movies_subset(),
aes_string(x = input$x, y = input$y, color = input$z)
) +
geom_point() +
labs(title = pretty_plot_title())
})
# Create descriptive text
output$description <- renderText({
paste0("The plot above titled '", pretty_plot_title(), "' visualizes the relationship between ", input$x, " and ", input$y, ", conditional on ", input$z, ".")
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
### Practice - Find inconsistencies in what the app is reporting
In this exercise we go on a hunt for mismatched used of reactives.
#### Your turn
- Run the sample code and view the app. Do the number of movies plotted match the number cited in the text below the app?
- If not, fix the app code.
::: proj
*Complete the exercise by navigating to the RStudio Cloud Project titled **3-2b Find inconsistencies in what the app is reporting** in your RStudio Workspace*
[<i class="fa fa-cloud"></i> Go to RStudio Cloud Project](https://rstudio.cloud/spaces/81721/join?access_code=I4VJaNsKfTqR3Td9hLP7E1nz8%2FtMg6Xbw9Bgqumv){.btn .test-drive}
:::
```{r ex-3-2b-inconsistencies, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
library(dplyr)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
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"
),
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"
),
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"
),
checkboxGroupInput(
inputId = "selected_type",
label = "Select movie type(s):",
choices = c("Documentary", "Feature Film", "TV Movie"),
selected = "Feature Film"
),
numericInput(
inputId = "n_samp",
label = "Sample size:",
min = 1, max = nrow(movies),
value = 3
)
),
mainPanel(
plotOutput(outputId = "scatterplot"),
uiOutput(outputId = "n")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
# Create a subset of data filtering for selected title types
movies_subset <- reactive({
req(input$selected_type)
filter(movies, title_type %in% input$selected_type)
})
# Create new df that is n_samp obs from selected type movies
movies_sample <- reactive({
req(input$n_samp)
sample_n(movies_subset(), input$n_samp)
})
# Create scatterplot object the plotOutput function is expecting
output$scatterplot <- renderPlot({
ggplot(data = movies_sample(), aes_string(x = input$x, y = input$y, color = input$z)) +
geom_point()
})
# Print number of movies plotted
output$n <- renderUI({
types <- factor(movies_subset()$title_type, levels = input$selected_type)
counts <- table(types)
HTML(paste("There are", counts, input$selected_type, "movies plotted in the plot above. <br>"))
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)
```
<details>
<summary>
Show solution
</summary>
See the following code chunk for the solution to the exercise above.
```{r ex-3-2b-inconsistencies-solution, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
library(dplyr)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
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"
),
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"
),
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"
),
checkboxGroupInput(
inputId = "selected_type",
label = "Select movie type(s):",
choices = c("Documentary", "Feature Film", "TV Movie"),
selected = "Feature Film"
),
numericInput(
inputId = "n_samp",
label = "Sample size:",
min = 1, max = nrow(movies),
value = 3
)
),
mainPanel(
plotOutput(outputId = "scatterplot"),
uiOutput(outputId = "n")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
# Create a subset of data filtering for selected title types
movies_subset <- reactive({
req(input$selected_type)
filter(movies, title_type %in% input$selected_type)
})
# Create new df that is n_samp obs from selected type movies
movies_sample <- reactive({
req(input$n_samp)
sample_n(movies_subset(), input$n_samp)
})
# Create scatterplot object the plotOutput function is expecting
output$scatterplot <- renderPlot({
ggplot(data = movies_sample(), aes_string(x = input$x, y = input$y, color = input$z)) +
geom_point()
})
# Print number of movies plotted
output$n <- renderUI({
types <- movies_sample()$title_type %>%
factor(levels = input$selected_type)
counts <- table(types)
HTML(paste("There are", counts, input$selected_type, "movies plotted in the plot above. <br>"))
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
## 3.3 Reactives and observers
In this section we discuss implementations of the three different types of reactive objects.
### Reactive flow
As we go through the different implementations, I recommend that you think back to where they appear on the reactive flow chart.
```{r image-rective-flow}
knitr::include_graphics("images/reactive-flow.png")
```
### Reactive inputs
An implementation of reactive inputs is `reactiveValues()`.
One example is user inputs (`input$*`). The input object is a reactive value that looks like a list, and contains many individual reactive values that are set by input from the web browser.
### Reactive expressions
You can create reactive expressions with the `reactive()` function.
An example is the reactive data frame subsets we created in the earlier sections and exercises.
- Reactive expressions can access reactive values or other reactive expressions, and they return a value.
- They are useful for caching the results of any procedure that happens in response to user input.
### Implementation of reactive outputs
And lastly, the implementation for reactive outputs is observers.
For example, an `output$*` object is a reactive observer. Actually, under the hood a render function returns a reactive expression, and when you assign this reactive expression to an `output$*` value, Shiny automatically creates an observer that uses the reactive expression.
- Observers can access reactive inputs and reactive expressions, but they don't return a value.
- Instead they are used for their **side effects**, which typically involves sending data to the web browser.
### Reactives vs. observers
To help these concepts sink in a bit more, let's compare reactives vs. observers.
#### Similarities
Both store expressions that can be executed
#### Differences
- Reactive expressions return values, but observers do not.
- Observers eagerly respond to reactives, but reactive expressions do not.
- Reactive expressions must not have side effects, while observers are only useful for their side effects.
#### Most importantly
- We use the `reactive()` function when calculating values, without side effects.
- We use the `observe()` function when performing actions, with side effects.
- The moral of the story is to not use `observe()` when calculating a value, and to especially not use `reactive()` for performing actions with side effects.
###
Here is a summary table of the differences between reactives and observers.