-
Notifications
You must be signed in to change notification settings - Fork 4
/
Chapter5.Rmd
353 lines (288 loc) · 10.3 KB
/
Chapter5.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
---
title: "Chapter 5"
author: "Maya Gans"
date: "3/29/2020"
output: html_document
css: styles.css
---
## 5.8.1
Draw the reactive graph for each app.
#### Prototype
<img src="www/reactlog1.png"></img>
#### Y-Axis
<img src="www/reactlog2.png"></img>
#### Narrative
<img src="www/reactlog3.png"></img>
## 5.8.2
What happens if you flip `fct_infreq()` and `fct_lump()` in the code that reduces the summary tables?
Using a test factor we see that we have 3 `a`s and 2 `c`s. if we first `fct_lump`, then every letter with a count of 2 will be placed into `Other`. `Other` now has 4 values so this becomes the 1st first factor when we factor based on frequency using `fct_infreq`. Because `Other` really represents different letters it should be placed as the last factor in our order.
```{r, eval=FALSE}
test <- factor(c("a", "a", "a", "c", "c", "b", "d", "e", "f"))
fct_infreq(fct_lump(test$a, n = 2))
```
## 5.8.3
Add an input control that lets the user decide how many rows to show in the summary tables.
Our function `count_top` is responsible for grouping our variables into a set number of factors, lumping the rest of the values into `other`. The function has an argument `n` which is set to `5`. By creating a `numericInput` called `rows` we can let the user set the number of `fct_infreq` dynamically. However because `fct_infreq` is the number of factors + `Other`, we need to subtract 1 from what the user selects in order to display the number of rows they input.
:::note
I tried downloading the data using the neiss package but I think that's already been cleaned. The data for this app can be found here: https://github.com/hadley/mastering-shiny/tree/master/neiss
:::
```{r, eval=FALSE}
library(shiny)
library(tidyr)
count_top <- function(df, var, n = 5) {
df %>%
mutate({{ var }} := fct_lump(fct_infreq({{ var }}), n = n)) %>%
group_by({{ var }}) %>%
summarise(n = as.integer(sum(weight)))
}
fct_infreq(fct_lump(test$a, n = 2))
injuries <- vroom::vroom("injuries.tsv.gz")
products <- vroom::vroom("products.tsv")
population <- vroom::vroom("population.tsv")
selected <- injuries %>% filter(prod_code == 1842)
ui <- fluidPage(
fluidRow(
column(8,
selectInput("code", "Product",
choices = setNames(products$prod_code, products$title),
width = "100%"
)
),
column(2, numericInput("rows", "Number of Rows", min = 0, max = 10, value = 5)),
column(2, selectInput("y", "Y axis", c("rate", "count")))
),
fluidRow(
column(4, tableOutput("diag")),
column(4, tableOutput("body_part")),
column(4, tableOutput("location"))
),
fluidRow(
column(12, plotOutput("age_sex"))
),
fluidRow(
column(2, actionButton("story", "Tell me a story")),
column(10, textOutput("narrative"))
)
)
server <- function(input, output, session) {
selected <- reactive(injuries %>% filter(prod_code == input$code))
# use counter() for the n argument in count_top
counter <- reactive(input$rows - 1)
output$diag <- renderTable(count_top(selected(), diag, n = counter()), width = "100%")
output$body_part <- renderTable(count_top(selected(), body_part, n = counter()), width = "100%")
output$location <- renderTable(count_top(selected(), location, n = counter()), width = "100%")
summary <- reactive({
selected() %>%
count(age, sex, wt = weight) %>%
left_join(population, by = c("age", "sex")) %>%
mutate(rate = n / population * 1e4)
})
output$age_sex <- renderPlot({
if (input$y == "count") {
summary() %>%
ggplot(aes(age, n, colour = sex)) +
geom_line() +
labs(y = "Estimated number of injuries") +
theme_grey(15)
} else {
summary() %>%
ggplot(aes(age, rate, colour = sex)) +
geom_line(na.rm = TRUE) +
labs(y = "Injuries per 10,000 people") +
theme_grey(15)
}
})
output$narrative <- renderText({
input$story
selected() %>% pull(narrative) %>% sample(1)
})
}
shinyApp(ui, server)
```
## 5.8.4
Provide a way to step through every narrative systematically with forward and backward buttons.
```{r, eval=FALSE}
# data downloaded from https://github.com/hadley/mastering-shiny/tree/master/neiss
# this is not == the neiss package data!
library(shiny)
library(tidyr)
count_top <- function(df, var, n = 5) {
df %>%
mutate({{ var }} := fct_lump(fct_infreq({{ var }}), n = n)) %>%
group_by({{ var }}) %>%
summarise(n = as.integer(sum(weight)))
}
fct_infreq(fct_lump(test$a, n = 2))
injuries <- vroom::vroom("injuries.tsv.gz")
products <- vroom::vroom("products.tsv")
population <- vroom::vroom("population.tsv")
selected <- injuries %>% filter(prod_code == 1842)
ui <- fluidPage(
fluidRow(
column(8,
selectInput("code", "Product",
choices = setNames(products$prod_code, products$title),
width = "100%"
)
),
column(2, numericInput("rows", "Number of Rows", min = 0, max = 10, value = 5)),
column(2, selectInput("y", "Y axis", c("rate", "count")))
),
fluidRow(
column(4, tableOutput("diag")),
column(4, tableOutput("body_part")),
column(4, tableOutput("location"))
),
fluidRow(
column(12, plotOutput("age_sex"))
),
fluidRow(
column(2, actionButton("prev_story", "Go back a story")),
column(2, actionButton("next_story", "Next story")),
column(8, textOutput("narrative"))
)
)
server <- function(input, output, session) {
selected <- reactive(injuries %>% filter(prod_code == input$code))
counter <- reactive(input$rows - 1)
output$diag <- renderTable(count_top(selected(), diag, n = counter()), width = "100%")
output$body_part <- renderTable(count_top(selected(), body_part, n = counter()), width = "100%")
output$location <- renderTable(count_top(selected(), location, n = counter()), width = "100%")
summary <- reactive({
selected() %>%
count(age, sex, wt = weight) %>%
left_join(population, by = c("age", "sex")) %>%
mutate(rate = n / population * 1e4)
})
output$age_sex <- renderPlot({
if (input$y == "count") {
summary() %>%
ggplot(aes(age, n, colour = sex)) +
geom_line() +
labs(y = "Estimated number of injuries") +
theme_grey(15)
} else {
summary() %>%
ggplot(aes(age, rate, colour = sex)) +
geom_line(na.rm = TRUE) +
labs(y = "Injuries per 10,000 people") +
theme_grey(15)
}
})
# set values$count to 1
values <- reactiveValues(count = 1)
# when next story is select increase values$count
observeEvent(input$next_story, {
values$count <- values$count + 1
})
# when next story is select decrease values$count
observeEvent(input$prev_story, {
values$count <- values$count - 1
})
# use values$count as the index of the story chosen
output$narrative <- renderText({
print(values$count)
selected()$narrative[values$count]
})
}
```
Advanced: Make the list of narratives “circular” so that advancing forward from the last narrative takes you to the first.
```{r, eval=FALSE}
# data downloaded from https://github.com/hadley/mastering-shiny/tree/master/neiss
# this is not == the neiss package data!
library(shiny)
library(tidyr)
count_top <- function(df, var, n = 5) {
df %>%
mutate({{ var }} := fct_lump(fct_infreq({{ var }}), n = n)) %>%
group_by({{ var }}) %>%
summarise(n = as.integer(sum(weight)))
}
fct_infreq(fct_lump(test$a, n = 2))
injuries <- vroom::vroom("injuries.tsv.gz")
products <- vroom::vroom("products.tsv")
population <- vroom::vroom("population.tsv")
selected <- injuries %>% filter(prod_code == 1842)
ui <- fluidPage(
fluidRow(
column(8,
selectInput("code", "Product",
choices = setNames(products$prod_code, products$title),
width = "100%"
)
),
column(2, numericInput("rows", "Number of Rows", min = 0, max = 10, value = 5)),
column(2, selectInput("y", "Y axis", c("rate", "count")))
),
fluidRow(
column(4, tableOutput("diag")),
column(4, tableOutput("body_part")),
column(4, tableOutput("location"))
),
fluidRow(
column(12, plotOutput("age_sex"))
),
fluidRow(
column(2, actionButton("prev_story", "Go back a story")),
column(2, actionButton("next_story", "Next story")),
column(8, textOutput("narrative"))
)
)
server <- function(input, output, session) {
selected <- reactive(injuries %>% filter(prod_code == input$code))
# to check the code is working I changed the select code to only the head
# in order to loop through just 6 values
selected <- reactive(head(injuries %>% filter(prod_code == input$code)))
counter <- reactive(input$rows - 1)
output$diag <- renderTable(count_top(selected(), diag, n = counter()), width = "100%")
output$body_part <- renderTable(count_top(selected(), body_part, n = counter()), width = "100%")
output$location <- renderTable(count_top(selected(), location, n = counter()), width = "100%")
summary <- reactive({
selected() %>%
count(age, sex, wt = weight) %>%
left_join(population, by = c("age", "sex")) %>%
mutate(rate = n / population * 1e4)
})
output$age_sex <- renderPlot({
if (input$y == "count") {
summary() %>%
ggplot(aes(age, n, colour = sex)) +
geom_line() +
labs(y = "Estimated number of injuries") +
theme_grey(15)
} else {
summary() %>%
ggplot(aes(age, rate, colour = sex)) +
geom_line(na.rm = TRUE) +
labs(y = "Injuries per 10,000 people") +
theme_grey(15)
}
})
values <- reactiveValues(count = 1)
observeEvent(input$next_story, {
# if the count is the max number of selected rows
# then go back to 1
if (values$count < nrow(selected())) {
values$count <- values$count + 1
} else {
values$count <- 1
}
})
observeEvent(input$prev_story, {
# if you're at the first story go to the last story
# otherwise can go down in index number
if (values$count == 1) {
values$count <- nrow(selected())
} else {
values$count <- values$count - 1
}
})
output$narrative <- renderText({
# check we're incrementing up and back to 1
# and when we reach one we go back up to 6
# print(values$count)
selected()$narrative[values$count]
})
}
shinyApp(ui, server)
```