-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathChapter8.Rmd
More file actions
568 lines (434 loc) · 15.1 KB
/
Copy pathChapter8.Rmd
File metadata and controls
568 lines (434 loc) · 15.1 KB
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
---
title: "Chapter 8"
author: "Maya Gans"
date: "3/29/2020"
output: html_document
css: styles.css
---
## 8.1.5.1
Complete the user interface below with a server function that updates `input$date` so that you can only select dates in `input$year`.
```{r, eval=FALSE}
ui <- fluidPage(
numericInput("year", "year", value = 2020),
dateInput("date", "date")
)
```
This solution was a little wonky because it required shinyjs for the dateInput to properly update. I [opened up an issue here](https://github.com/rstudio/shiny/issues/2798) since I think this is not the most intuative answer.
```{r, eval=FALSE}
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs() ,
numericInput("year", "year", value = 2020),
dateInput("date", "date", value = Sys.Date())
)
server <- function(input, output, session) {
observeEvent(input$year, {
req(input$year) # stop if year is blank
daterange <- range(as.Date(paste0(input$year, "-01-01")),as.Date(paste0(input$year, "-12-31")))
updateDateInput(session, "date", min = daterange[1], max = daterange[2] )
delay(250, # delay 250ms
updateDateInput(session,"date",
value = daterange[1]
))
})
}
shinyApp(ui = ui, server = server)
```
## 8.1.5.2
Complete the user interface below with a server function that updates `input$county` choices based on `input$state`. For an added challenge, also change the label from “County” to “Parrish” for Louisana and “Borrough” for “Alaska”.
```{r, eval=FALSE}
library(openintro)
states <- unique(county$state)
ui <- fluidPage(
selectInput("state", "State", choices = states),
selectInput("county", "County", choices = NULL)
)
```
```{r, eval=FALSE}
library(shiny)
library(tidyverse)
library(openintro)
states <- unique(county$state)
counties <- unique(county$state)
ui <- fluidPage(
selectInput("state", "State", choices = states),
selectInput("county", "County", choices = NULL)
)
server <- function(input, output, session) {
label <- reactive({
switch(input$state,
"Alaska" = "Burrough",
"Louisiana" = "Parish",
"County")
})
observeEvent( input$state, {
updateSelectInput(session, "county", label = label(),
choices = county %>%
filter(state == input$state) %>%
select(name) %>%
distinct())
})
}
shinyApp(ui = ui, server = server)
```
## 8.1.5.3
Complete the user interface below with a server function that updates `input$country` choices based on the `input$continent`. Use `output$data` to display all matching rows.
```{r, eval=FALSE}
library(gapminder)
continents <- unique(gapminder$continent)
ui <- fluidPage(
selectInput("continent", "Continent", choices = continents),
selectInput("country", "Country", choices = NULL),
tableOutput("data")
)
```
```{r, eval=FALSE}
library(shiny)
library(gapminder)
continents <- unique(gapminder$continent)
ui <- fluidPage(
selectInput("continent", "Continent", choices = c("", as.character(continents))),
selectInput("country", "Country", choices = NULL),
tableOutput("data")
)
server <- function(input, output, session) {
selected_data <- reactive({
if(input$continent %in% continents) {
gapminder %>%
filter(continent == input$continent)
} else {
gapminder
}
})
observeEvent( input$continent, {
updateSelectInput(session, "country", "Country",
choices = selected_data() %>%
select(country) %>%
distinct())
})
output$data <- renderTable({
selected_data() %>%
filter(country == input$country)
})
}
shinyApp(ui = ui, server = server)
```
## 8.1.5.4
Extend the previous app so that you can also choose to select no continent, and hence see all countries. You’ll need to add "" to the list of choices, and then handle that specially when filtering.
:::note
Initially setting the choices to `c("", as.character(continents))` allows the user to see all the Country options prior to a continent being selected. That said, once a continent is selected this `""` option is no longer available.
<br>
<a href="https://github.com/tanho63">@tanho63</a> suggests:
"You can use <tt>"All"</tt> instead of <tt>""</tt> - not sure why it's recalculating continent when evaluated, reactivelog wasn't very helpful on it."
:::
```{r, eval=FALSE}
library(shiny)
library(gapminder)
continents <- unique(gapminder$continent)
ui <- fluidPage(
selectInput("continent", "Continent", choices = c("", as.character(continents))),
# @tanho63:
# selectInput("continent", "Continent", choices = c("All", as.character(continents))),
selectInput("country", "Country", choices = NULL),
tableOutput("data")
)
server <- function(input, output, session) {
selected_data <- reactive({
if(input$continent %in% continents) {
gapminder %>%
filter(continent == input$continent)
} else {
gapminder
}
})
observeEvent( input$continent, {
# @tanho63:
updateSelectInput(session, "country",
choices = unique(selected_data()$country))
})
output$data <- renderTable({
selected_data() %>%
filter(country == input$country)
})
}
shinyApp(ui = ui, server = server)
```
## 8.1.5.5
What is at the heart of the problem described at https://community.rstudio.com/t/29307?
Updating all three sliders creates a circular reference!
## 8.4.3.1
Take this very simple app based on the initial example in the chapter:
```{r, eval=FALSE}
ui <- fluidPage(
selectInput("type", "type", c("slider", "numeric")),
uiOutput("numeric")
)
server <- function(input, output, session) {
output$numeric <- renderUI({
if (input$type == "slider") {
sliderInput("n", "n", value = 0, min = 0, max = 100)
} else {
numericInput("n", "n", value = 0, min = 0, max = 100)
}
})
}
```
How could you instead implement it using dynamic visibility? If you implement dynamic visiblity, how could you keep the values in sync when you change the controls?
```{r, eval=FALSE}
library(shiny)
parameter_tabs <- tagList(
tags$style("#params { display:none; }"),
tabsetPanel(id = "params",
tabPanel("slider",
sliderInput("my_slider", "n", value = 0, min = 0, max = 100)
),
tabPanel("numeric",
numericInput("my_numeric", "n", value = 0, min = 0, max = 100)
)
)
)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("my_selector", "Input Type",
choices = c("slider", "numeric")
),
parameter_tabs,
),
mainPanel()
)
)
server <- function(input, output, session) {
# if slider changes, update numeric
observeEvent( input$my_slider, {
updateNumericInput(session, "my_numeric", value = isolate(input$my_slider))
})
# if numeric changes update slider
observeEvent( input$my_numeric, {
updateSliderInput(session, "my_slider", value = isolate(input$my_numeric))
})
observeEvent(input$my_selector, {
updateTabsetPanel(session, "params", selected = input$my_selector)
})
}
shinyApp(ui = ui, server = server)
```
## 8.4.3.2
Add support for date and date-time columns `make_ui()` and `filter_var()`.
In order to complete this, I had to
1) make a new dummy dataframe I called `x` in order to test for dates
2) include checking for `is.Date` in the `make_ui` and `filter_var` functions
3) Change `tableOutput` and `renderTable` to `DT::renderTableOutput` and `DT::renderTableOutput` becuase `renderTable` was rendering the dates as numbers and I think this could be because it uses `xtable()` for HTML table rendering?
```{r, eval=FALSE}
# 8.4.3.2
library(shiny)
library(purrr)
library(tidyverse)
make_ui <- function(x, var) {
if (is.numeric(x)) {
rng <- range(x, na.rm = TRUE)
sliderInput(var, var, min = rng[1], max = rng[2], value = rng)
} else if (is.factor(x)) {
levs <- levels(x)
selectInput(var, var, choices = levs, selected = levs, multiple = TRUE)
} else if (lubridate::is.Date(x)) {
rng <- range(x, na.rm = TRUE)
dateInput(var, var, min = rng[1], max = rng[2], value = rng[1])
} else {
# No control, so don't filter
NULL
}
}
filter_var <- function(x, val) {
if (is.numeric(x)) {
!is.na(x) & x >= val[1] & x <= val[2]
} else if (is.factor(x)) {
x %in% val
} else if (lubridate::is.Date(x)) {
x %in% val
} else {
TRUE
}
}
library(shiny)
dfs <- keep(ls("package:datasets"), ~ is.data.frame(get(.x, "package:datasets")))
# add a dataframe with dates in it since I cant find one in the datasets above
# rep 5 dates five times, each include 1 factor a-e
x <- data.frame(date = c(rep(as.Date("2020/1/1"), 5),
rep(as.Date("2020/2/2"), 5),
rep(as.Date("2020/3/3"), 5),
rep(as.Date("2020/4/4"), 5),
rep(as.Date("2020/5/5"), 5)),
fac = as.factor(c("a", "b", "c", "d", "e")))
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
#selectInput("dataset", label = "Dataset", choices = c(dfs, "x")),
uiOutput("filter")
),
mainPanel(
DT::dataTableOutput("data")
)
)
)
server <- function(input, output, session) {
# data is either my dummy dataset or from datasets
data <- reactive(x)
vars <- reactive(names(data()))
output$filter <- renderUI(
# take eahc column name and make ui
# data()[[.x]] is each column
# and .x is each column name (vars())
map(vars(), ~ make_ui(data()[[.x]], .x))
)
selected <- reactive({
# take each column name and filer var
# with the first argument the column in the data
# and the second argument the input$vars()
# so for date check that input[[date]] in data[[1]]
each_var <- map(vars(), ~ filter_var(data()[[.x]], input[[.x]]))
# notes from @mapaulacaldas
# collapse list of TRUE and FALSE using `&`
# conditions <- list(TRUE, TRUE, TRUE, FALSE)
# purrr::reduce(conditions, `&`) ==
# ((conditions[[1]] & conditions[[2]]) & conditions[[3]]) & conditions[[4]]
reduce(each_var, `&`)
})
# subset the data by the vars that are true
output$data <- DT::renderDataTable(data()[selected(), ])
}
# Run the application
shinyApp(ui = ui, server = server)
```
## 8.4.3.3
(Advanced) If you know the S3 OOP system, consider how you could replace the if blocks in `make_ui()` and `filter_var()` with generic functions.
```{r, eval=FALSE}
library(shiny)
library(purrr)
make_ui <- function(obj, var) { UseMethod("make_ui") }
make_ui.numeric <- function(x, var) {
rng <- range(x, na.rm = TRUE)
sliderInput(var, var, min = rng[1], max = rng[2], value = rng)
}
make_ui.factor <- function(x, var) {
levs <- levels(x)
selectInput(var, var, choices = levs, selected = levs, multiple = TRUE)
}
make_ui.default <- function(x, var) { NULL }
filter_var <- function(x, val) { UseMethod("filter_var") }
filter_var.numeric <- function(x, val) { !is.na(x) & x >= val[1] & x <= val[2] }
filter_var.factor <- function(x, val) { x %in% val }
filter_var.default <- function(x, val) { TRUE }
dfs <- keep(ls("package:datasets"), ~ is.data.frame(get(.x, "package:datasets")))
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("dataset", label = "Dataset", choices = dfs),
uiOutput("filter")
),
mainPanel(
tableOutput("data")
)
)
)
server <- function(input, output, session) {
data <- reactive({
get(input$dataset, "package:datasets")
})
vars <- reactive(names(data()))
output$filter <- renderUI(
map(vars(), ~ make_ui(data()[[.x]], .x))
)
selected <- reactive({
each_var <- map(vars(), ~ filter_var(data()[[.x]], input[[.x]]))
reduce(each_var, `&`)
})
output$data <- renderTable(head(data()[selected(), ], 12))
}
shinyApp(ui = ui, server = server)
```
## 8.4.3.4 TODO
(Hard) Make a wizard that allows the user to upload their own dataset. The first page should handle the upload. The second should handle reading it, providing one drop down for each variable that lets the user select the column type. The third page should provide some way to get a summary of the dataset.
:::note
I wasn't really sure what was meant by "some way to get a summary of the dataset" So I'm just using the summary function.
:::
```{r, eval=FALSE}
library(shiny)
library(readr)
make_dropdown <- function(name_of_vector) {
selectInput(inputId = name_of_vector, label = name_of_vector, choices =
c("numeric", "character", "logical"))
}
ui <- fluidPage(
tags$style("#wizard { display:none; }"),
tabsetPanel(id = "wizard",
tabPanel("page1",
fileInput("data_input", "input"),
actionButton("page12", "next")
),
tabPanel("page2",
sidebarLayout(
sidebarPanel(
uiOutput("type_of")
),
mainPanel(
tableOutput('type_table')
)),
actionButton("page21", "prev"),
actionButton("page23", "next")
),
tabPanel("page3",
tableOutput("summary_table"),
actionButton("page32", "prev")
)
)
)
server <- function(input, output, session) {
################ WIZARD ###############################
switch_tab <- function(page) {
updateTabsetPanel(session, "wizard", selected = page)
}
observeEvent(input$page12, switch_tab("page2"))
observeEvent(input$page21, switch_tab("page1"))
observeEvent(input$page23, switch_tab("page3"))
observeEvent(input$page32, switch_tab("page2"))
##################### FILE INPUT #######################
dat <- reactive({
req(input$data_input)
read.csv(input$data_input$datapath)
})
##################### TABLE TYPE #######################
# make a dropdown using the names of each column
output$type_of <- renderUI({ map(names(dat()), ~ make_dropdown(.x)) })
# switch the type of column based on the input
# name of vector == "Sepal.Length"
# vector == Sepal.Length
change_type <- function(vector, name_of_vector) {
switch(input[[name_of_vector]],
"numeric" = vector <- as.numeric(vector),
"character" = vector <- as.character(vector),
"logical" = vector <- as.complex(vector)
)
}
# convert the supplied data to a list
# use imap because it is a condensed version o map
# with two arguments == x & name_of_x
# so we don't need to supply it arguments beyond the list!
df<- reactive({
dat() %>%
as.list() %>%
imap(change_type) %>%
as_tibble()
})
# create an output of the data's names
# and their types
output$type_table <- renderTable(data.frame(
names = names(df()),
type = map_chr(df(), function(x) typeof(x)))
)
##################### TABLE OUTPUT #####################
output$summary_table <- renderTable( summary(df()) )
}
shinyApp(ui = ui, server = server)
```