forked from r4ds/bookclub-mshiny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
04-case_study_er_injuries.Rmd
323 lines (243 loc) · 7.58 KB
/
04-case_study_er_injuries.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
# Case study: ER injuries
**Learning objectives:**
- Learn how to **create a more complex Shiny app**
- Get an idea **how to build your app based on your data exploration**
- Learn how to **create your app step-by-step**
- Get more comfortable **using the techniques you learned so far**
## Introduction
This Chapter is about building a more complex app with the tools we learned in the previous chapters.
We're going to use the following packages:
```{r package-list, message=FALSE, warning=FALSE}
library(shiny)
library(vroom)
library(tidyverse)
```
## The data
We're exploring data from the National Electronic Injury Surveillance System (NEISS), which covers **accidents reported from a sample of hospitals in the US**.
For every accident / inured person we have
- **date**,
- **age**,
- **sex**,
- **race**,
- **body part**,
- **diagnosis** and
- **location** (Home, School, Street Or Highway etc.)
as well as
- **primary product** associated with the injury and
- **a brief story** how the accident occured.
Further we have a **weight** attribute for an estimation how may people the current case represents if the dataset was scaled to the entire US population.
Code to download the data:
```{r download-data}
dir.create("neiss")
download <- function(name) {
url <- "https://github.com/hadley/mastering-shiny/raw/master/neiss/"
download.file(paste0(url, name), paste0("neiss/", name), quiet = TRUE)
}
download("injuries.tsv.gz")
download("population.tsv")
download("products.tsv")
```
Main data:
```{r main-data, message=FALSE}
injuries <- vroom("neiss/injuries.tsv.gz")
injuries
```
Product names:
```{r product-data, message=FALSE}
products <- vroom("neiss/products.tsv")
products
```
Population data:
```{r population-data, message=FALSE}
population <- vroom("neiss/population.tsv")
population
```
## Exploration
As motivation for the app we want to build, we're going to explore the data.
Let's have a look at accidents related to toilets:
```{r no-toilets}
# product code for toilets is 649
selected <- injuries %>%
filter(prod_code == 649)
nrow(selected)
```
We're interested in how many accidents related to toilets we see for different locations, body parts and diagnosis.
```{r count-toilets}
selected %>%
count(location, wt = weight, sort = TRUE)
selected %>%
count(body_part, wt = weight, sort = TRUE)
selected %>%
count(diag, wt = weight, sort = TRUE)
```
Next we'll we create a plot for the number of accidents for different age and sex:
```{r line-plot}
summary <- selected %>%
count(age, sex, wt = weight) %>%
left_join(y = population, by = c("age", "sex")) %>%
mutate(rate = n / population * 1e4)
summary %>%
ggplot(mapping = aes(x = age, y = rate, color = sex)) +
geom_line(na.rm = TRUE) +
labs(y = "Injuries per 10,000 people")
```
The goal is to build an app, which outputs the tables and the plot for different products, which the user selects.
## Prototype
The first version of the app is a dashboard, where the user can choose a product and get the tables and the plot we have seen in the previous chapter.
Code of the ui:
```{r prototype-ui, eval=FALSE}
ui <- fluidPage(
# choose product
fluidRow(
column(
width = 6,
selectInput(inputId = "code", label = "Product", choices = prod_codes)
)
),
# display tables
fluidRow(
column(width = 4, tableOutput(outputId = "diag")),
column(width = 4, tableOutput(outputId = "body_part")),
column(width = 4, tableOutput(outputId = "location"))
),
# display plot
fluidRow(
column(width = 12, plotOutput(outputId = "age_sex"))
)
)
```
Code of the server:
```{r prototype-server, eval=FALSE}
server <- function(input, output, session) {
# reactive for filtered data frame
selected <- reactive(
injuries %>%
filter(prod_code == input$code)
)
# render diagnosis table
output$diag <- renderTable(
selected() %>%
count(diag, wt = weight, sort = TRUE)
)
# render body part table
output$body_part <- renderTable(
selected() %>%
count(body_part, wt = weight, sort = TRUE)
)
# render location table
output$location <- renderTable(
selected() %>%
count(location, wt = weight, sort = TRUE)
)
# reactive for plot data
summary <- reactive(
selected() %>%
count(age, sex, wt = weight) %>%
left_join(y = population, by = c("age", "sex")) %>%
mutate(rate = n / population * 1e4)
)
# render plot
output$age_sex <- renderPlot(
expr = {
summary() %>%
ggplot(mapping = aes(x = age, y = n, colour = sex)) +
geom_line() +
labs(y = "Estimated number of injuries")
},
res = 96
)
}
```
_Note:_ The reactive for plot data is only used once. You could also compute the dataframe when rendering the plot, but it is good practise to **seperate computing and plotting**. It's easier to understand and generalise.
This prototype is available at https://hadley.shinyapps.io/ms-prototype/.
Now we're going to improve the app step-by-step.
## Polish tables
The prototype version of the app has very long tables. To make it a little clearer we only want to show the top 5 and lump together all other categories in every table.
As an example the diagnosis table for all products would look like this:
```{r diag-table}
injuries %>%
mutate(diag = fct_lump(fct_infreq(diag), n = 5)) %>%
group_by(diag) %>%
summarise(n = as.integer(sum(weight)))
```
## Rate vs count
Next step is to give the user the chance to plot the data relative to 10,000 People or in absolute numbers.
The new ui looks like this:
```{r rate-count-ui, eval=FALSE}
ui <- fluidPage(
fluidRow(
column(
width = 8,
selectInput(
inputId = "code",
label = "Product",
choices = prod_codes,
width = "100%"
)
),
column(
width = 2,
selectInput(inputId = "y", label = "Y axis", choices = c("rate", "count"))
)
),
fluidRow(
column(width = 4, tableOutput(outputId = "diag")),
column(width = 4, tableOutput(outputId = "body_part")),
column(width = 4, tableOutput(outputId = "location"))
),
fluidRow(
column(width = 12, plotOutput(outputId = "age_sex"))
)
)
```
And plot rendering changes to:
```{r rate-count-server, eval=FALSE}
server <- function(input, output, session) {
...
output$age_sex <- renderPlot(
expr = {
if (input$y == "count") {
summary() %>%
ggplot(mapping = aes(x = age, y = n, colour = sex)) +
geom_line() +
labs(y = "Estimated number of injuries")
} else {
summary() %>%
ggplot(mapping = aes(x = age, y = rate, colour = sex)) +
geom_line(na.rm = TRUE) +
labs(y = "Injuries per 10,000 people")
}
},
res = 96
)
}
```
## Narrative
Now we want a button to sample an accident story related to the currently chosen product and display it.
We add the following ui elements:
```{r narrative-ui, eval=FALSE}
ui <- fluidPage(
...
fluidRow(
column(
width = 2,
actionButton(inputId = "story", label = "Tell me a story")
),
column(width = 10, textOutput(outputId = "narrative"))
)
)
```
In the backend we need an `eventReactive` that triggers, when the button is clicked or the selected data changes:
```{r narrative-server, eval=FALSE}
server <- function(input, output, session) {
...
narrative_sample <- eventReactive(
eventExpr = list(input$story, selected()),
valueExpr = selected() %>%
pull(narrative) %>%
sample(1)
)
output$narrative <- renderText(narrative_sample())
}
```
The resulting version of the app is available at https://hadley.shinyapps.io/ms-prototype/.