forked from PsyTeachR/shiny-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-first-app.Rmd
372 lines (261 loc) · 14.4 KB
/
01-first-app.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
---
title: "First Shiny App"
output:
html_document:
self_contained: no
toc: yes
toc_depth: 2
code_folding: show
toc_float:
collapsed: false
number_sections: true
---
In this tutorial, I'm going to walk you through the basics of setting up a shiny app, starting with the example built into RStudio. I'm not going to explain yet how shiny apps are structured, the goal is to just get something up and running, and give you some familiarity with the layout of a fairly simple app.
* Knowledge: [Basic RStudio and R](https://gupsych.github.io/data_skills/01_intro.html)
* Programs: [R](http://cran.r-project.org/mirrors.html) and [RStudio](https://www.rstudio.com/products/rstudio/download3/)
* Packages: `shiny`, `ggplot2`
* Time: ~ 30 minutes
# Create the Demo App
<input type="checkbox" class="progress">
## New project...
Under the `File` menu, choose `New Project...`. You will see a popup window like the one below. Choose `New Directory`.
![](images/01-first-app/01-create-project.png)
<input type="checkbox" class="progress">
## Project type
Choose `Shiny Web Application` as the project type.
![](images/01-first-app/02-project-type.png)
<input type="checkbox" class="progress">
## Directory name
I like to put all of my apps in the same directory, but it doesn't matter where you save it.
![](images/01-first-app/03-project-directory.png)
<input type="checkbox" class="progress">
## Default demo app
Your RStudio interface should look like this now. You don't have to do anything else at this step.
![](images/01-first-app/04-rstudio-interface.png)
<p class="alert alert-warning">If RStudio has changed their demo app and your source code doesn't look like this, replace it with the code below:</p>
```{r demo-rstudio, eval = F}
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
}
# Run the application
shinyApp(ui = ui, server = server)
```
<input type="checkbox" class="progress">
## Run the app
Click on `Run App` in the top right corner of the [source pane](defs.html#panes). The app will open up in a new window. Play with the slider and watch the histogram change.
![](images/01-first-app/05-app-interface.png)
<p class="alert alert-info">You can also open up the app in a web browser by clicking on `Open in Browser`.</p>
# Modify the Demo App
Now we're going to make a series of changes to the demo app until it's all your own.
<p class="alert alert-info">You can close the app by closing the window or browser tab it's running in, or leave it running while you edit the code. If you have multiple screens, it's useful to have the app open on one screen and the code on another.</p>
<input type="checkbox" class="progress">
## Change the title
Find the application title. It is the first [argument](defs.html#argument) to the [function](defs.html#function) `titlePanel`. Change the title to `"My First App"`. Make sure the title is inside quotes and the whole quoted [string](defs.html#string) is inside the parentheses. Save the file (`cmd-S` or `File > Save`).
![](images/01-first-app/06-change-title.png)
<input type="checkbox" class="progress">
## Reload the app
Click `Run App` (or `Reload App` if you haven't closed the app window) in the [source pane](defs.html#panes). If you haven't saved your changes, it will prompt you to do so. Check that the app title has changed.
<input type="checkbox" class="progress">
## Change the input
Find the function `sliderInput` (line 21). The first [argument](defs.html#argument) is the name you can use in the code to find the value of this input, so don't change it just yet. The second [argument](defs.html#argument) is the text that displays before the slider. Change this to something else and re-run the app.
```{r, app-sliderInput, eval = F}
sliderInput("bins",
"Number of bins:",
min = 0,
max = 50,
value = 30)
```
<p class="alert alert-tryit">See if you can figure out what the next three arguments to `sliderInput` do. Change them to different integers, then re-run the app to see what's changed.</p>
<input type="checkbox" class="progress">
## Add some text
The arguments to the function `sidebarPanel` are just a list of things you want to display in the sidebar. To add some explanatory text in a paragraph before the `sliderInput`, just use the paragraph function `p("My text")`
```{r, app-sidebar-p, eval = F}
sidebarPanel(
p("I am explaining this perfectly"),
sliderInput("bins",
"Choose the best bin number:",
min = 10,
max = 40,
value = 25)
)
```
![](images/01-first-app/07-app-sidebar-p.png)
<p class="alert alert-info">The sidebar shows up on the left if your window is wide enough, but moves to the top of the screen if it's too narrow.</p>
<input type="checkbox" class="progress">
## Move the text
I don't like it there, so we can move this text out of the sidebar and to the top of the page, just under the title. Try this and re-run the app.
```{r, app-intro-text, eval = F}
# Application title
titlePanel("My First App"),
p("I am explaining this perfectly"),
# Sidebar with a slider input for number of bins
sidebarLayout(...)
```
<p class="alert alert-tryit">See where you can move the text in the layout of the page and where causes errors.</p>
<input type="checkbox" class="progress">
## Change the plot colour
I'm also not keen on the grey plot. We can change it inside the `hist` function.
```{r plot-colors, eval = F}
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'steelblue3', border = 'grey30')
```
There are a lot of ways to represent colour in R. The easiest three are:
1. hexadecimal colours like `#0066CC`,
2. the `rgb` or `hsl` functions,
3. colour names (see page 4 of Melanie Frazier's [R color cheetsheet](https://www.nceas.ucsb.edu/~frazier/RSpatialGuides/colorPaletteCheatsheet.pdf)
I like `steelblue3`, as it's pretty close to the shiny intereface default colour, but feel free to choose whetever you like.
<input type="checkbox" class="progress">
## Change the plot style
I prefer `ggplot` graphs, so let's make the plot with `geom_histogram` instead of `hist` (which is a great function for really quick plots). Since we need several functions from the `ggplot2` [package](defs.html#package), we'll need to load that package at the top of the script, just under where the `shiny` package is loaded:
```{r load-library, eval = F}
library(shiny)
library(ggplot2)
```
You can replace all of the code in the `renderPlot` function with the code below.
```{r, ggplot, eval = F}
output$distPlot <- renderPlot({
# create plot
ggplot(faithful, aes(waiting)) +
geom_histogram(bins = input$bins,
fill = "steelblue3",
colour = "grey30") +
xlab("What are we even plotting here?") +
theme_minimal()
})
```
<p class="alert alert-info">You can set the `fill` and `colour` to whatever colours you like, and change `theme_minimal()` to one of the other [built-in ggplot themes](https://ggplot2.tidyverse.org/reference/ggtheme.html#examples).</p>
<p class="alert alert-tryit">What *are* we even plotting here? Type `?faithful` into the console pane to see what the `waiting` column represents (`faithful` is a built-in demo dataset). Change the label on the x-axis to something more sensible.</p>
# Adding New Things
<input type="checkbox" class="progress">
## Add a new input widget
The `faithful` dataset includes two columns:`eruptions` and `waiting`. We've been plotting the `waiting` variable, but what if you wanted to plot the `eruptions` variable instead?
<p class="alert alert-tryit">Try plotting the eruption time (`eruptions`) instead of the waiting time. You just have to change one word in the `ggplot` function and update the x-axis label.</p>
We can add another input widget to let the user switch between plotting eruption time and wait time. The [RStudio Shiny tutorial](https://shiny.rstudio.com/tutorial/written-tutorial/lesson3/) has a great overview of the different input options. We need to toggle between two options, so we can use either radio buttons or a select box. Radio buttons are probably best if you have only a few options and the user will want to see them all at the same time to decide.
Add the following code as the first argument to `sidebarPanel()`, which just takes a list of different [widgets](defs.html#widget). `radioButtons` is the widget we're using. The first argument is `display_var`, which we will use later in the code to find the value of this widget. The second argument is the label to display to the user. The next argument is `choices`, which is a list of choices in the format `c("label1" = "value1", "label2 = "value2", ...)`. The label is what gets shown to the user and the value is what gets used by the code (these can be the same, but you often want the user label to be more descriptive). The last argument is `selected`, which is the value of the default choice. Save this and re-run the app.
```{r add-radiobuttons, eval = F}
radioButtons("display_var",
"Which variable to display",
choices = c("Waiting time to next eruption" = "waiting",
"Eruption time" = "eruptions"),
selected = "waiting"
),
```
![](images/01-first-app/08-radiobutton-widget.png)
You should have a radio button interface now. You can click on the options to switch the button, but it won't do anything to your plot yet. We need to edit the plot-generating code to make that happen.
<input type="checkbox" class="progress">
## Change what you're plotting
First, we need to change the x-axis label depending on what we're graphing. We use an if/else statement to set the variable `xlabel` to one thing if `input$display_var` is equivalent to `"eruptions"`, and to something else if it's equivalent to `"waiting"`. Put this code at the very beginning of the code block for the `renderPlot` function (after the line `output$distPlot <- renderPlot({`).
```{r plot-switch1, eval = F}
# set x-axis label depending on the value of display_var
if (input$display_var == "eruptions") {
xlabel <- "Eruption Time (in minutes)"
} else if (input$display_var == "waiting") {
xlabel <- "Waiting Time to Next Eruption (in minutes)"
}
```
<p class="alert alert-warning">The double-equal-signs `==` means "equivalent to and is how you check if two things are the same; if you only use one equal sign, you set the variable on the left to the value on the right.</p>
Then we have to edit the `ggplot` function to use the new label and to plot the right column. Notice that the function `aes(waiting)` from before has changed to `aes_string(input$display_var)`. The variable `input$display_var` gives you the user-input value of the widget called `display_var`.
```{r plot-switch2, eval = F}
# create plot
ggplot(faithful, aes_string(input$display_var)) +
geom_histogram(bins = input$bins,
fill = "steelblue3",
colour = "grey30") +
xlab(xlabel) +
theme_minimal()
```
<p class="alert alert-warning">The change from `aes` to `aes_string` is a quirk of `ggplot`; if you need to use [strings](defs.html#string) to specify the names of the columns to display, you have to use `aes_string`. The value of `display_var` is a string, so we have to do it this way.</p>
Re-run your app and see if you can change the data and x-axis label with your new widget. If not, check that your code against the code below:
```{r example-code, eval = F}
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(ggplot2)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("My First App"),
p("I am explaining this perfectly"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
radioButtons("display_var",
"Which variable to display",
choices = c("Waiting time to next eruption" = "waiting",
"Eruption time" = "eruptions"),
selected = "waiting"
),
sliderInput("bins",
"Number of bins:",
min = 10,
max = 40,
value = 25)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# set x-axis label depending on the value of display_var
if (input$display_var == "eruptions") {
xlabel <- "Waiting Time to Next Eruption (in minutes)"
} else if (input$display_var == "waiting") {
xlabel <- "Waiting Time to Next Eruption (in minutes)"
}
# create plot
ggplot(faithful, aes_string(input$display_var)) +
geom_histogram(bins = input$bins,
fill = "steelblue3",
colour = "grey30") +
xlab(xlabel) +
theme_minimal()
})
}
# Run the application
shinyApp(ui = ui, server = server)
```