-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflow.qmd
2252 lines (1552 loc) · 67.1 KB
/
flow.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
# Reactive Flow
```{r setup, include=FALSE}
library(shiny)
library(tidyverse)
library(rsconnect)
knitr::opts_chunk$set(
echo = FALSE,
fig.align = "center",
out.width = "100%"
)
```
## Reactive flow
### Reactivity, in spreadsheets
One familiar way of thinking about reactivity is to think in the context of a spreadsheet, like Google Sheets or Microsoft Excel.
```{r, out.width = "80%"}
knitr::include_graphics("images/spreadsheet-1.png")
```
###
Suppose you write a value into a cell in a spreadsheet...
```{r, out.width = "80%"}
knitr::include_graphics("images/spreadsheet-2.png")
```
###
and then in another cell you write a formula that depends on that cell.
```{r, out.width = "80%"}
knitr::include_graphics("images/spreadsheet-3.png")
```
###
First, the formula is calculated with the value you originally typed.
```{r, out.width = "80%"}
knitr::include_graphics("images/spreadsheet-4.png")
```
###
Now when you change the value of the original cell, the result of the formula will automatically update, or in other words, react to this change.
```{r, out.width = "80%"}
knitr::include_graphics("images/spreadsheet-5.png")
```
### Reactions
In a Shiny app reactivity happens in a similar fashion.
Suppose you have a `sliderInput` in your app with the `inputId` of `alpha`. The value of this input is stored in `input$alpha`.
```{r}
knitr::include_graphics("images/slider-alpha.png")
```
So when the user moves around the slider, the value of the alpha input is updated in the input list.
### Reactivity 101
Reactivity automatically occurs when an input value is used to render an output object, i.e. in the `server` function below the plot is re-rendered when the value of `input$alpha` changes based on user input. You, as the app developer, do not need to write code that says *"Update the plot every time the value of `input$alpha` changes"*, Shiny automatically takes care of this for you in the `render*()` function.
```{r}
knitr::include_graphics("images/server-alpha.png")
```
### Reactive flow
Here is a roadmap of the reactive flow in Shiny, though for now we'll just focus on the straight path between an input and an output, and discuss the other features later in the course.
```{r, out.width = "100%"}
knitr::include_graphics("images/reactive-flow.png")
```
### Reactive flow, simplified
```{r, out.width = "100%"}
knitr::include_graphics("images/reactive-flow-simple.png")
```
The user selects an input, this input goes through some expression in the server, and an output is rendered. Each time the user changes their input selection, the expression that generates the output will automatically re-execute, and the relevant output will be re-rendered based on the new value of the input.
In a Shiny application, there's no need to explictly describe the relationships between inputs and outputs and tell R what to do when each input changes, Shiny automatically handles these details for you.
### Practice: Building a reactive widget
As we saw in the previous sections, reactivity is established by linking an input with an output via a `render*()` function.
#### Your turn
- Add a new input widget, a `sliderInput`, that controls the transparency of the plotted points. This widget should have the ID `alpha` and its values should range between 0 and 1. You can decide what the displayed label and initial value of the slider should be.
- Make the associated update in the server function.
::: proj
*Complete the exercise by navigating to the RStudio Cloud Project titled **2-1a Building a reactive widget** 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-2-1a-build-reactive, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(inputId = "y",
label = "Y-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "audience_score"),
selectInput(inputId = "x",
label = "X-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "critics_score"),
# Set alpha level
sliderInput(inputId = ___,
label = ___,
min = ___, max = ___,
value = ___)
),
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x, y = input$y)) +
geom_point(alpha = ___)
})
}
# 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-2-1a-build-reactive-solution, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "y",
label = "Y-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "audience_score"
),
selectInput(
inputId = "x",
label = "X-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "critics_score"
),
sliderInput(
inputId = "alpha",
label = "Alpha:",
min = 0, max = 1,
value = 0.5
)
),
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x, y = input$y)) +
geom_point(alpha = input$alpha)
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
### Practice: Dude, where's my plot?
The server function of this app builds two plots, `scatterplot` and `densityplot`, however the app only displays one.
#### Your turn
- Run the app and identify which plot is missing
- Make the necessary update to the app UI to display the missing plot
- Reduce the height of the new plot using the `height` argument in the `plotOutput()` function (suggested height: `height = 200`)
*Hint:* Make sure you place commas as appropriate.
::: proj
*Complete the exercise by navigating to the RStudio Cloud Project titled **2-1b Dude wheres my plot** 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-2-1b-where-plot, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(inputId = "y",
label = "Y-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "audience_score"),
selectInput(inputId = "x",
label = "X-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "critics_score")
),
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x, y = input$y)) +
geom_point()
})
output$densityplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x)) +
geom_density()
})
}
# 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-2-1b-where-plot-solution, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "y",
label = "Y-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "audience_score"
),
selectInput(
inputId = "x",
label = "X-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "critics_score"
)
),
mainPanel(
plotOutput(outputId = "scatterplot"),
plotOutput(outputId = "densityplot", height = 200)
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x, y = input$y)) +
geom_point()
})
output$densityplot <- renderPlot({
ggplot(data = movies, aes_string(x = input$x)) +
geom_density()
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
## UI Inputs
###
The goal of this section is to build familiarity with a few UI input functions.
###
Once again, we'll build on our simple movie browser app.
```{r, out.width = "100%"}
knitr::include_graphics("images/app-selectinput-scatterplot.png")
```
###
Shiny provides a wide selection of input widgets. The Shiny cheatsheet is a great place to see a list of them all at once.
Once you know which one you want to use, you can find out more about it in the package documentation. You'll also get a chance to work with some of them in the following exercises.
```{r, out.width = "80%"}
knitr::include_graphics("images/cheatsheet-inputs.png")
```
### checkboxInput
Let's start with a `checkboxInput()`.
Suppose we want to add checkbox input to our app to specify whether the data plotted should be shown in a data table. We need to make three modifications to our app to accomplish this.
1. In the **ui**: Add an input widget that the user can interact with to check/uncheck the box.
1.In the **ui**: Add an output to the UI defining where the data table should appear.
1. In the **server** function: Add a reactive expression that creates the data table if the checkbox is checked.
We'll go through these steps one by one.
### 1. **ui**: Add an input widget that the user can interact with to check/uncheck the box
```{r, eval = FALSE, echo = TRUE}
# Show data table
checkboxInput(inputId = "show_data",
label = "Show data table",
value = TRUE)
```
- The first argument is the `inputId`, which we can define to be anything we want, but short and informative names are the best.
- Next is the `label`, which is the user facing description of the widget.
- And last is the `value`, the initial value of the widget. `TRUE` means the box is initially checked. If you want it to not be checked initially, you'd set it to `FALSE` instead.
### Watch for commas!
A cautionary tale before we move on -- watch for your commas! Remember that this widget definition goes in the `sidebarPanel()`. In this panel we separate out widget with commas.
```{r snippet-commas, echo = TRUE, eval = FALSE}
sidebarPanel(
# Select variable for y-axis
selectInput(inputId = "y", label = "Y-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score", "audience_score", "runtime"),
selected = "audience_score"),
# Select variable for x-axis
selectInput(inputId = "x", label = "X-axis:",
choices = c("imdb_rating", "imdb_num_votes", "critics_score",
"audience_score", "runtime"),
selected = "critics_score"),
# Show data table
checkboxInput(inputId = "show_data",
label = "Show data table", value = TRUE)
)
```
```{r, out.width = "80%"}
knitr::include_graphics("images/commas.png")
```
For example:
- The first is the `selectInput` widget for y, then we have a comma,
- then another `selectInput` and another comma, and
- then our new `checkboxInput` and no comma after it since it's the last item in the list.
### 2. **ui**: Add an output to the UI defining where the data table should appear.
```{r snippet-dt, eval = FALSE, echo = TRUE}
mainPanel(
# Show scatterplot
plotOutput(outputId = "scatterplot"),
# Show data table
dataTableOutput(outputId = "movestable")
)
```
The second step was to add an output to the UI defining where the data table should appear. Note that for this we're using the `dataTableOutput()` function.
This function takes one argument, the `outputId`. Again, you can define to be anything we want, but short and informative names are the best.
### 3. **server**: Add a reactive expression that creates the data table if the checkbox is checked.
```{r, eval = FALSE, echo = TRUE}
# Print data table if checked
output$moviestable <- renderDataTable({
if(input$show_data){
DT::datatable(data = movies %>% select(1:7),
options = list(pageLength = 10),
rownames = FALSE)
}
})
```
Lastly, in our server, we describe how this table should be calculated. We use the `renderDataTable()` function to build this table.
Note that the first line of code in the function is an if statement, telling the app to only do this if `input$show_data` is `TRUE`. We also specify some other arguments to `datatable()`, mostly for cosmetic reasons.
###
Here is the resulting app, with the box **checked**:
```{r, out.width = "80%"}
knitr::include_graphics("images/app-datatable-checked.png")
```
and box **unchecked**:
```{r, out.width = "80%"}
knitr::include_graphics("images/app-datatable-unchecked.png")
```
### Scoping
A quick note on scoping:
We saw that the data loaded on top of the Shiny app, outside of ui and server definitions, is visible to the server. That's how we were able to plot the data simply by referring to the data frame by name. The data frame is actually also visible to the UI as well. So our UI inputs could be defined programmatically.
We'll give an example for this, not with an interactive widget but instead with a static HTML statement:
```{r, eval = FALSE, echo = TRUE}
# Display number of observations
HTML(paste0("The dataset has ", nrow(movies),
"observations."))
```
### Practice: Add numericInput
The app below allows users to randomly select a desired number of movies, and displays some information on the selected movies in a tabular output. This table is created using a new function, `renderDataTable()`, but for now we will keep our focus on the `numericInput()` widget. We will also learn to define variables outside of the app so that they can be used in multiple spots to make our code more efficient.
#### Your turn
- Make sure entries in the `sidebarPanel()` are separated by commas
- Calculate `n_total` (total number of movies in the data set) as `nrow(movies)` before defining the UI.
- Use `n_total` instead of the hard-coded `"651"` in the helper text.
- Add `min` and `max` values to the `numericInput()` widget, where min is 1 and max is `n_total`.
- Change the default `value` of the sample size to 30.
- Change the `step` parameter of `numericInput()` such that values increase by 1 (instead of 10) when the up arrow is clicked in the numeric input widget in the app UI.
::: proj
*Complete the exercise by navigating to the RStudio Cloud Project titled **2-2a Add numericInput** 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-2-2a-numericInput, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
library(dplyr)
library(DT)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
HTML(paste("Enter a value between 1 and", "651"))
numericInput(inputId = "n",
value = 3,
step = 10)
),
mainPanel(
DT::dataTableOutput(outputId = "moviestable")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$moviestable <- DT::renderDataTable({
movies_sample <- movies %>%
sample_n(input$n) %>%
select(title:studio)
DT::datatable(data = movies_sample,
options = list(pageLength = 10),
rownames = FALSE)
})
}
# 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-2-2a-numericInput-solution, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
library(dplyr)
library(DT)
# Load data --------------------------------------------------------------------
load("movies.RData")
n_total <- nrow(movies)
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
HTML(paste("Enter a value between 1 and", n_total)),
numericInput(
inputId = "n",
label = "Sample size:",
value = 30,
min = 1, max = n_total,
step = 1
)
),
mainPanel(
dataTableOutput(outputId = "moviestable")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$moviestable <- renderDataTable({
movies_sample <- movies %>%
sample_n(input$n) %>%
select(title:studio)
DT::datatable(
data = movies_sample,
options = list(pageLength = 10),
rownames = FALSE
)
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
### Practice: req
The app below is the one you developed in the previous exercise.
- Highlight the code and run it.
- Then, delete the numeric value.
You will encounter an error: `Error: size is not a numeric or integer vector`.
In order to avoid such errors, which users of your app could very easily encounter, we need to hold back the output from being calculated if the input is missing.
The `req()` function is the simplest and best way to do this, it ensures that values are available ("[truthy](https://shiny.rstudio.com/reference/shiny/latest/req.html)") before proceeding with a calculation or action. If any of the given values is not truthy, the operation is stopped by raising a "silent" exception (not logged by Shiny, nor displayed in the Shiny app's UI).
#### Your turn
- Add `req(input$n)` in the `renderDataTable()` function in the server before `movies_sample` is calculated.
- Run your app again and delete the input sample size to confirm that the error doesn't appear, and neither does the output table.
::: proj
*Complete the exercise by navigating to the RStudio Cloud Project titled **2-2b req** 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-2-2b-req, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
options("shiny.sanitize.errors" = FALSE) # Turn off error sanitization
# Load data --------------------------------------------------------------------
load("movies.RData")
n_total <- nrow(movies)
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
HTML(paste("Enter a value between 1 and", n_total)),
numericInput(inputId = "n",
label = "Sample size:",
value = 30,
min = 1, max = n_total,
step = 1)
),
mainPanel(
DT::dataTableOutput(outputId = "moviestable")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$moviestable <- DT::renderDataTable({
movies_sample <- movies %>%
sample_n(input$n) %>%
select(title:studio)
datatable(data = movies_sample,
options = list(pageLength = 10),
rownames = FALSE)
})
}
# Create a 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-2-2b-req-solution, echo = FALSE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
options("shiny.sanitize.errors" = FALSE) # Turn off error sanitization
# Load data --------------------------------------------------------------------
load("movies.RData")
n_total <- nrow(movies)
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
HTML(paste("Enter a value between 1 and", n_total)),
numericInput(
inputId = "n",
label = "Sample size:",
value = 30,
min = 1, max = n_total,
step = 1
)
),
mainPanel(
dataTableOutput(outputId = "moviestable")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$moviestable <- renderDataTable({
req(input$n)
movies_sample <- movies %>%
sample_n(input$n) %>%
select(title:studio)
datatable(
data = movies_sample,
options = list(pageLength = 10),
rownames = FALSE
)
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
### Practice: Select to selectize
The app below can be used to display movies from selected studios. Currently you can only choose one studio, but we'll modify it to allow for multiple selections. Additionally, there are 211 unique studios represented in this dataset, we need a better way to select than to scroll through such a long list, and we address that with the `selectize` option, which will suggest names of studios as you type them.
#### Your turn
- View the help function for the `selectInput` widget by typing `?selectInput` in the console, and figure out how to enable the `selectize` and `multiple` selection options (or whether they are enabled by default).
- Based on your findings add the necessary arguments to the `selectInput` widget.
- Add a call to the `req()` function in the server, just like you did in the previous exercise but this time `req`uiring that `input$studio` be available.
- Run the app and (1) confirm that you can select multiple studios, (2) start typing "Warner Bros" to confirm `selectize` works, and (3) delete all selections to confirm `req` is preventing an error from being displayed.
- Now try with `selectize = FALSE`: Start typing "Warner Bros" and see how the behaviour changed.
::: proj
*Complete the exercise by navigating to the RStudio Cloud Project titled **2-2c Select to selectize** 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-2-2c-selectize, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
library(dplyr)
library(DT)
# Load data --------------------------------------------------------------------
load("movies.RData")
all_studios <- sort(unique(movies$studio))
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(inputId = "studio",
label = "Select studio:",
choices = all_studios,
selected = "20th Century Fox")
),
mainPanel(
DT::dataTableOutput(outputId = "moviestable")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$moviestable <- renderDataTable({
movies_from_selected_studios <- movies %>%
filter(studio == input$studio) %>%
select(title:studio)
DT::datatable(data = movies_from_selected_studios,
options = list(pageLength = 10),
rownames = FALSE)
})
}
# Create a 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-2-2c-selectize-solution, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
library(dplyr)
library(DT)
# Load data --------------------------------------------------------------------
load("movies.RData")
all_studios <- sort(unique(movies$studio))
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Input(s)
sidebarPanel(
selectInput(
inputId = "studio",
label = "Select studio:",
choices = all_studios,
selected = "20th Century Fox",
multiple = TRUE
)
),
# Output(s)
mainPanel(
dataTableOutput(outputId = "moviestable")
)
)
)
# Server
server <- function(input, output, session) {
# Create data table
output$moviestable <- renderDataTable({
req(input$studio)
movies_from_selected_studios <- movies %>%
filter(studio %in% input$studio) %>%
select(title:studio)
DT::datatable(
data = movies_from_selected_studios,
options = list(pageLength = 10),
rownames = FALSE
)
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
### Practice: Convert `dateInput` to `dateRangeInput`
The app below can be used to display movies from a particular date onwards. Instead we would like to select movies between two given dates. Hence we need to convert the `dateInput` widget to `dateRangeInput`. This input will yield a vector (`input$date`) of length two: the first element is the start date and the second is the end date.
#### Your turn
- Review the help files for the two widgets by typing `?dateInput` and `?dateRangeInput` in the console.
- Update `dateInput` to `dateRangeInput`, instead of just a start date (`value`) specify `start` and `end` dates, Jan 1, 2013 and Jan 1, 2014, respectively.
- Update the explanatory text to reflect the new functionality of the app.
- Change the `startview` to `"year"` to make it a bit easier for the user to navigate the calendar.
- Update how subsetting is being done in the server function: we need movies released at or after the start date and at or before the end date.
- Add the necessary `req` statement to the server to stop the app from trying to create a plot when no dates are specified.
::: proj
*Complete the exercise by navigating to the RStudio Cloud Project titled **2-2d Convert dateInput to dateRangeInput** 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-2-2d-dates, echo = TRUE, eval = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
library(dplyr)
# Load data --------------------------------------------------------------------
load("movies.RData")
min_date <- min(movies$thtr_rel_date)
max_date <- max(movies$thtr_rel_date)
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
sidebarPanel(