-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhello.qmd
1080 lines (727 loc) · 37.7 KB
/
hello.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
---
always_allow_html: true
---
# Getting Started
```{r setup, include=FALSE}
library(shiny)
library(tidyverse)
library(rsconnect)
knitr::opts_chunk$set(
echo = FALSE,
fig.align = "center",
out.width = "100%"
)
```
## Here is a Shiny app
And not just any app, an app that you will be able to build by the end of this tutorial!
```{r, context = "data", cache = TRUE}
load("movies.RData")
```
```{r}
knitr::include_app("https://minecr.shinyapps.io/movies/", height = "1200px")
```
We'll go through the technical details of each component of such an app throughout the tutorial, but for now let's take a high level view.
```{r}
knitr::include_graphics("images/shiny-app-annotated.png")
```
We have:
- a title for the app,
- a series of inputs:
- some of these inputs use drop down menus for selection,
- some are sliders,
- some allow for text input, and
- some are action buttons
- and a few outputs:
- a plot output that the user can interactively update,
- a text output that updates alongside it, and
- a data table output that also updates alongside these.
As much as it looks like there is a lot going on in this sample app, the app doesn't even scratch the surface of what you can build with Shiny.
I hope you're excited to take it all in!
## Background
Before we get started with Shiny, let's talk background...
This tutorial assumes that you are familiar with R as a programming language.
Additionally, this tutorial uses packages from the [tidyverse](https://tidyverse.org/) (e.g. [**dplyr**](https://dplyr.tidyverse.org/) for data wrangling and [**ggplot2**](https://ggplot2.tidyverse.org/) for data visualisation). Your Shiny apps can use any package, but if you'd like to learn more about doing data science with the tidyverse, see [here](https://www.tidyverse.org/learn/).
## Help
The tutorial is designed for beginners and many of the exercises have plenty of scaffolding to help you along the way.
That being said, there are a few other resources that might help your learning.
```{r, out.width = "80%"}
knitr::include_graphics("images/help.png")
```
1. The first is the [**Shiny cheatsheet**](https://github.com/rstudio/cheatsheets/raw/master/shiny.pdf). This is a handy-dandy [cheatsheet](https://rstudio.com/resources/cheatsheets/) that I recommend you keep close by when building Shiny apps.
2. The second is the [**Shiny homepage**](https://shiny.rstudio.com). It is *the* place to learn about all things Shiny and to keep up to date with it as it evolves.
## Tips
Also, let's go over three very important tips for learning to develop Shiny apps:
1. Always **run the entire script** containing the R code, not just up to the point where you're developing code. For most exercises in this tutorial you will be asked to modify or update existing Shiny code, and even though you might be altering a small portion of the code, you still need to run the entire app code to create the app.
2. Sometimes the best way to troubleshoot is to **run the app and review the error**. Not only can the error message be informative, but googling the error message might quickly land you on a solution.
3. **Watch out for commas!** This will mean more as you start to learn Shiny, but just keep in mind, a Shiny error can often be caused by a missing comma. Thankfully, the RStudio IDE will alert you to most of these missing comma or similar syntax errors, like the one shown below.
```{r, out.width = "30%"}
knitr::include_graphics("images/missing-comma-ide.png")
```
## Anatomy of a Shiny app
Alrighty, let's take a look at the anatomy of a Shiny app:
```{r, out.width = "80%"}
knitr::include_graphics("images/anatomy.png")
```
- We start by loading any necessary packages, one of which is necessarily shiny.
- Then we lay out the user interface with a ui object that controls the appearance of our app.
- And we define the server function that contains instructions needed to build the app.
- We end each Shiny app script with a call to the shinyApp() function that puts these two components together to create the Shiny app object.
## Data
In this tutorial we will build a simple movie browser app.
We will use data from the movies dataset, which combines data from two websites: the Internet Movie Database, commonly known as IMDB, and Rotten Tomatoes. The observations are a random sample of 651 movies released in the US between 1970 and 2014.
So where does the loading of the data happen in an app?
## Revisit
Let's revisit the app layout from a couple sections back.
```{r, out.width = "80%"}
knitr::include_graphics("images/revisit.png")
```
We load the data before `ui` and `server` definitions so that it can be used in both.
Alright, time for some practice!
## Practice: What's in an app?
Which of these is not generally a part of the Shiny app architecture?" - A function that installs an R package - User interface - Server function - A function that creates Shiny app objects
Answer: A function that installs an R package. You don't want to reinstall the package every time you run your app, so you should do this once in your console instead of within your Shiny app
## Practice: First peek under the hood
Below you can see the complete code to reproduce the app we introduced in the previous section. Now you get to interact with the app yourself, and make small adjustments to it.
I've created an RStudio Cloud Project for you to test drive this code. Click the button below to be taken to your RStudio Workspace, select **1.1 First peek under the hood** from the Project list, and follow the exercise instructions below to get started!
::: proj
*Navigate to the project called **1-1 First peek under the hood** after clicking the button below*
[<i class="fa fa-cloud"></i> Go to RStudio Cloud Workspace](https://rstudio.cloud/spaces/81721/join?access_code=I4VJaNsKfTqR3Td9hLP7E1nz8%2FtMg6Xbw9Bgqumv){.btn .test-drive}
:::
## Your turn
- Once your RStudio Cloud Project is open to the script `app.R`, click <img src="images/run-app.png" alt="Run App" height="25px"/> to run the code and generate the app.
- Play with the input selectors for the Y-axis and the X-axis and observe how the output changes.
- Close the app by closing the pop-up window or clicking on the red Stop button in the viewer.
- Locate the relevant lines of code in `app.R` that build the selector widget for the Y-axis. This is in a `selectInput()` function starting on Line 20, underneath the comment `# Select variable for y-axis`. Note that this function takes four arguments: `inputId`, `label`, `choices`, and `selected`. We'll discuss what each of these mean in detail shortly. For now, change the `selected` argument to `imdb_rating`, save your changes, and run the app again by clicking on <img src="images/run-app.png" alt="Run App" height="25px"/>. What changed?
- If you get an error when you try to rerun the app, you can either try to debug the issue by tracing back your steps or delete everything in `app.R` and copy and paste the code below into `app.R`. This will get you back to your starting point. You can use this "start over" approach for any of the exercises in this tutorial.
- Now locate the relevant lines of code in `app.R` that build the selector widget for the X-axis. This is also in a `selectInput()` function, starting on Line 27, underneath the comment `# Select variable for x-axis`. Change the `selected` argument to `imdb_rating` as well, save your changes, and run the app again. What changed?
```{r ex-1-1-selector, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
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"
)
),
# Output: Show scatterplot
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()
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
## User interface (UI)
###
In this section we'll build the user interface of a simple app.
However, before we get into the weeds of building a user interface, let's revisit the anatomy of a Shiny app.
```{r}
knitr::include_graphics("images/app-selectinput-scatterplot.png")
```
- The user interface, that we'll refer to as the "UI" going forward, defines and lays out the inputs of your app where users can make their selections. It also lays out the outputs.
- The server function, on the other hand, calculates outputs and performs any other calculations needed for the outputs.
### Example
```{r}
knitr::include_graphics("images/ui-to-scatterplot.png")
```
For example, if your app features a plot the code for building that plot lives in the server function. But the setup for the user defined inputs for the plot, as well as information on where physically on the app the plot should appear, are defined in the UI.
###
Here is the app we'll work with in this section and the code that builds the UI of that app.
Since this is too much code to parse, we'll explore individual components of the UI one by one.
```{r}
knitr::include_graphics("images/app-selectinput-scatterplot.png")
knitr::include_graphics("images/ui-selectinput-scatterplot.png")
```
### `fluidPage()`
At the outermost layer of our UI definition we begin with the `fluidPage()` function.
```{r}
knitr::include_graphics("images/fluidPage.png")
```
The `fluidPage()` function creates a fluid page layout consisting of rows and columns. Rows make sure that elements in them appear on the same line. Columns within these rows define how much horizontal space each element should occupy.
Fluid pages scale their components in realtime to fill all available browser width, which means you, the app developer, don't need to worry about defining relative widths for individual app components.
As always, for more information on arguments to this function, you can view the R function help by typing `?fluidPage` in your R console or visiting the function reference page on the package website [here](https://shiny.rstudio.com/reference/shiny/latest/).
### Layout
Next, we define the layout of our app with `sidebarLayout()`.
```{r}
knitr::include_graphics("images/layout.png")
```
Shiny includes a number of options for laying out the components of an application. The default layout, the one we're using in our example app, is a layout with a sidebar, that you can define with the `sidebarLayout()` function.
```{r}
knitr::include_graphics("images/layout-app.png")
```
This is a simple layout with a narrow sidebar for inputs and a wider main area for output.
Under the hood, Shiny implements layout features available in Bootstrap 2, which is a popular HTML/CSS framework. However the nice thing about working in Shiny is that no prior experience with Bootstrap is necessary.
To learn more about various layouts, I recommend reviewing the [Application Layout Guide article](https://shiny.rstudio.com/articles/layout-guide.html) at [shiny.rstudio.com](shiny.rstudio.com).
### Input controls
Next we define our sidebar panel containing input controls.
```{r}
knitr::include_graphics("images/input-controls.png")
```
###
This panel contains two dropdown menus created with the `selectInput()` function.
```{r}
knitr::include_graphics("images/input-dropdowns.png")
```
###
Let's take a look at one of the `selectInput` widgets a little more closely.
```{r}
knitr::include_graphics("images/input-closeup.png")
```
1. The first argument is the `inputId`, which is the input value that the app will internally use to access the value selected by the user.
2. The second argument is the `label`, which is the display label that the user sees.
3. The third argument is the list of `choices` the user will choose from. In this app, these are variable names from the movies dataset.
4. And lastly we specify a default selection from that list with `selected`.
### Main Panel
The final component of our UI is `mainPanel()`.
```{r}
knitr::include_graphics("images/main-panel.png")
```
Currently the main panel contains only one component, a plot output. We'll talk about how this plot is built later in the tutorial.
Next, let's practice building an app UI!
### Practice: Extend the UI
We'll start with a simplified version of the app you saw in the previous exercise. In this app a `selectInput()` widget is used to allow the user to select which variables should be plotted on the `x` and `y` axes of the scatterplot.
The `selectInput()` function has the following arguments:
- an `inputId` that is used to refer to the input parameter when building the scatterplot,
- a list of `choices` to pick from (which must match variable names in the data frame),
- and a `selected` choice for when the app first launches.
#### Your turn
Modify the Shiny app code in `app.R` / shown below:
- In the `ui`:
- Add a new `selectInput` widget to color the points by a choice of the following variables: `"title_type"`, `"genre"`, `"mpaa_rating"`, `"critics_rating"`, `"audience_rating"`.
- Make the default selection `"mpaa_rating"`.
- Use `"z"` as the `inputId`.
- `label` can be whatever you like.
- In the `server`:
- Set the color argument in `ggplot()` aesthetic mappings to `input$z`.
::: proj
*Complete this exercise by opening up the RStudio Project titled **1-2a Extend the UI** within your RStudio Cloud Workspace*
[<i class="fa fa-cloud"></i> Go to RStudio Cloud Workspace](https://rstudio.cloud/spaces/81721/join?access_code=I4VJaNsKfTqR3Td9hLP7E1nz8%2FtMg6Xbw9Bgqumv){.btn .test-drive}
:::
```{r ex-1-2a-selectInput, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
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"),
# Select variable for color
selectInput(inputId = "___",
label = "____",
choices = c(___),
selected = "___")
),
# Output: Show scatterplot
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,
color = ___)) +
geom_point()
})
}
# 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-1-2a-selectInput-solution, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
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"),
# Select variable for color
selectInput(inputId = "z",
label = "Color by:",
choices = c("title_type", "genre", "mpaa_rating", "critics_rating", "audience_rating"),
selected = "mpaa_rating")
),
# Output: Show scatterplot
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,
color = input$z)) +
geom_point()
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
### Practice: Extend the UI further
The potential variables the user can select for the `x` and `y` axes and `color` currently appear in the UI of the app the same way that they are spelled in the data frame header. However we might want to label them in a way that is more human readable. We can achieve this using named vectors for the `choices` argument, in the format of `"Human readable label" = "variable_name"`.
#### Your turn
- Fill in the blanks in the code below with human readable labels for `x` and `y` inputs.
- Re-create the `selectInput` widget for color, `z`, with options `"title_type"`, `"genre"`, `"mpaa_rating"`, `"critics_rating"`, and `"audience_rating"`, default selection `"mpaa_rating"` just like in the previous exercise, but this time use human readable labels as well.
::: proj
*Complete this exercise by opening up the RStudio Project titled **1-2b Extend the UI further** within your RStudio Cloud Workspace*
[<i class="fa fa-cloud"></i> Go to RStudio Cloud Workspace](https://rstudio.cloud/spaces/81721/join?access_code=I4VJaNsKfTqR3Td9hLP7E1nz8%2FtMg6Xbw9Bgqumv){.btn .test-drive}
:::
```{r ex-1-2b-selectInput-labels, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
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"),
# Select variable for color
selectInput(inputId = "z",
label = "Color:",
choices = ___,
selected = ___)
),
# Output: Show scatterplot
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,
color = input$z)) +
geom_point()
})
}
# 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-1-2b-selectInput-labels-solution, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
sidebarPanel(
# Select variable for y-axis
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"),
# Select variable for x-axis
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"),
# Select variable for color
# Select variable for color
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")
),
# Output: Show scatterplot
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,
color = input$z)) +
geom_point()
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
</details>
## Server function
Now that you've had some practice with the UI, it's time to move on to the server function.
Again, before we get into the details, let's remind ourselves of the anatomy of a Shiny app. The basic task of the server function is to define the relationship between inputs and outputs.
### Here again is the app that we are working with in this module
Earlier we saw how to build the UI of this app, and we also noted that each input was tagged with an `inputId` that can be used to refer to them in the server.
```{r}
knitr::include_graphics("images/app-selectinput-scatterplot.png")
```
### This is the server function code for this app
Once again there is a lot going on here to parse at once, so in the following sections we take a closer look at the function.
```{r}
knitr::include_graphics("images/server.png")
```
### At the outermost layer
```{r}
knitr::include_graphics("images/server-outermost.png")
```
We define our server function which takes two arguments: an `input` and an `output`. Both of these are named lists.
The server function accesses inputs selected by the user to perform computations and specifies how outputs laid out in the UI should be updated.
The server function can take on one more argument, `session`, which is an environment that can be used to access information and functionality relating to the session. However this concept is beyond the scope of this tutorial, so for now we'll stick to server functions that only have input and output arguments.
### `output`
Our simple app had only one output -- a plot. So our server function contains the logic necessary to build this plot.
```{r}
knitr::include_graphics("images/output.png")
```
The `renderPlot()` function specifies how the plot output should be updated. Let's take a look at what is happening in the `renderPlot()` function first.
### `renderPlot()`
```{r}
knitr::include_graphics("images/renderplot.png")
```
This is good ol' ggplot2 code! So even if you're new to shiny, if you've previously used ggplot2 for plotting in R, this syntax should look familiar to you.
One aspect of the syntax that might be new, however, is how the x and y variables are defined. They come from the input list that is built in the UI.
### Inputs
Here is the relevant UI and server code.
```{r}
knitr::include_graphics("images/inputs-x-y.png")
```
Input x and y come from the `selectInput()` widgets, and map to the `x` and `y` arguments of the plot aesthetics.
### Rules of server functions
There are three rules of building server functions:
1. Always save objects to display to the named output list, i.e. something of the form `output$xx`, where `xx` is the plot you want to display.
2. Always build objects to display with one of the `render*()` functions, like we built our plot with `renderPlot()`.
3. Use input values from the named input list, with `input$xx`.
### Output types
Just like various inputs, Shiny also provides a wide selection of output types each of which works with a render function.
```{r, out.width = "80%"}
knitr::include_graphics("images/cheatsheet-outputs.png")
```
For example, in our app we used the `renderPlot()` function to build our reactive plot (we'll get to what I mean by reactive in a second) and laid out the plot with the `plotOutput()` function.
```{r}
knitr::include_graphics("images/render-output-pairs.png")
```
Shiny knows to match these two together as they use the same `outputID`, scatterplot.
In the following exercises you'll get a chance to work with other render/output function pairs to add more elements to your app.
### Practice: Matching inputs and outputs
Here is a simple Shiny app. Try entering some text and observe how the text is displayed back to you after a short pause.
------------------------------------------------------------------------
```{r, eval = TRUE, echo = FALSE}
fluidPage(
textInput(inputId = "custom_text", label = "Input some text here:"),
strong("Text is shown below:"),
textOutput(outputId = "user_text")
)
```
\#`{r, context = "server", eval = TRUE} # output$user_text <- renderText({ input$custom_text }) #`
------------------------------------------------------------------------
The code for this app is given below, with a few pieces missing (indicated with `___`). Each of the blanks are numbered, e.g. (`[1]`, `[2]`, etc.)
```{r eval = FALSE, echo = TRUE}
library(shiny)
ui <- fluidPage(
textInput(
inputId = "custom_text",
label = "_[1]_"
),
strong("Text is shown below:"),
_[2]_(outputId = "_[3]_")
)
server <- function(input, output, session){
output$user_text <- renderText({ input$_[4]_ })
}
shinyApp(ui = ui, server = server)
```
\#`` {r mc-2} #question("Which of the following is false?", # answer('`[1]` should be `"Input some text here:"`', # message = "Take a look at the app, what text is #shown to the user above the text input area?"), # answer('`[2]` should be `textOutput`', # message = "Check out the Shiny cheatsheet for pairs #of input and output functions"), # answer('`[3]` should be `"custom_text"`', correct = TRUE), # answer('`[4]` should be `"custom_text"`', # message = "What is the ID of the input that should #be rendered?"), # allow_retry = TRUE #) # ``
### Reactivity
Let's also briefly discuss reactivity.
```{r, out.width = "80%"}
knitr::include_graphics("images/reactivity.png")
```
It's easy to build interactive applications with Shiny, but to get the most out of it, you'll need to understand the reactive programming scheme used by Shiny.
In a nutshell Shiny automatically updates outputs, such as plots, when inputs that go into them change.
### Putting all the pieces together
Before we wrap up this section, I should also mention the last component of each Shiny app, which is a call to the aptly named `shinyApp()` function, which puts the UI and the server pieces together to create a Shiny app object.
```{r, out.width = "80%"}
knitr::include_graphics("images/shinyAppfunction.png")
```
Time to put this all into practice!
### Practice: Rules of server functions
Which of the following is not true about server functions?
\#`` {r mc-3} #question("Which of the following is not true about server functions?", # answer("Server functions should include a call to #`runApp()`", # correct = TRUE, # message = "The `runApp()` function can be used in the Console to run a Shiny application, as an alternative to the Run App button in the RStudio IDE." # ), # answer("Objects to be displayed should be saved to #`output$`"), # answer("Reactive objects should be built with `render*()` functions"), # answer("Input values should be referred to with `input$`"), # allow_retry = TRUE, # random_answer_order = TRUE #) # ``
### Practice: Fix it up
Below is the code for the Shiny app we built earlier, however currently the code is broken. Specifically there are errors in the definition of the server function as well as in the `mainPanel` of the UI.
#### Your turn
- Review the app and identify errors in the code.
- Hint: Refer back to the rules of server functions.
- Do the render functions match the output functions? If not, make the appropriate change and try running the app. Are there any remaining errors?
- Are the inputs referred to using the correct syntax? If not, make the appropriate change and try running the app. Are there any remaining errors?
- Are the outputs referred to using the correct names? If not, make the appropriate change and try running the app. Are there any remaining errors?
::: proj
*Navigate to the project called **1-3 Fix it up** after clicking the button below*
[<i class="fa fa-cloud"></i> Go to RStudio Cloud Workspace](https://rstudio.cloud/spaces/81721/join?access_code=I4VJaNsKfTqR3Td9hLP7E1nz8%2FtMg6Xbw9Bgqumv){.btn .test-drive}
:::
```{r ex-1-3-fixup, eval = FALSE, echo = TRUE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
sidebarPanel(
# Select variable for y-axis
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"
),
# Select variable for x-axis
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"
),
# Select variable for color
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"
)
),
# Output: Show scatterplot
mainPanel(
plotOutput(outputId = "scatterPlot")
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
output$scatterplot <- renderTable({
ggplot(data = movies, aes_string(x = x, y = y, color = z)) +
geom_point()
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)
```
```{r ex-1-3-fixup-solution, include = FALSE}
# Load packages ----------------------------------------------------------------
library(shiny)
library(ggplot2)
# Load data --------------------------------------------------------------------
load("movies.RData")
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
sidebarLayout(
# Inputs: Select variables to plot
sidebarPanel(
# Select variable for y-axis
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"
),
# Select variable for x-axis
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"
),
# Select variable for color
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"
)
),
# Output: Show scatterplot
mainPanel(
plotOutput(outputId = "scatterplot")
)