forked from r4bds/r4bds.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlab09.qmd
647 lines (489 loc) · 32.7 KB
/
lab09.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
# Lab 9 Creating a Simple Shiny Application {.unnumbered}
## Package(s)
- [shiny](https://github.com/rstudio/shiny)
- [golem](https://engineering-shiny.org/index.html)
## Schedule
- 08.00 - 08.30: [Recap of Lab 8](https://raw.githack.com/r4bds/r4bds.github.io/main/recap_lab09.html)
- 08.30 - 09.00: [Lecture](https://raw.githack.com/r4bds/r4bds.github.io/main/lecture_lab09.html)
- 09.00 - 09.15: Break
- 09.00 - 12.00: [Exercises](#sec-exercises)
## Learning Materials
_Please prepare the following materials_
- Book: [Mastering Shiny](https://mastering-shiny.org/) by Hadley Wickham -- Read Chapter 1 (Chapter 2 and 3 are good to read as well, if you want).
- Book: [Engineering Production-Grade Shiny Apps](https://engineering-shiny.org/index.html) -- Read Chapter 2 - 5 (they are fairly short, but if you don't find Shiny Apps super cool, feel free to skip Chapter 3 and 5 and Sections 2.2.2 and 4.2.3 - 4.2.4), the rest are quite important for the exercises.
- Cheatsheet: [Shiny](https://raw.githubusercontent.com/rstudio/cheatsheets/main/shiny.pdf) -- This cheatsheet is a bit cluttered, but useful
- Cheatsheet: [Golem](https://raw.githubusercontent.com/rstudio/cheatsheets/main/golem.pdf) -- Look through this after reading the chapters in "Engineering Production-Grade Shiny Apps" - the exercises will remind you to look at the cheatsheet as well.
_Note: The following are suggested learning materials, i.e., do not go over everything, but poke around. You will use these materials as a point of reference for the group exercises_
- [Shiny Input Gallery](https://shiny.rstudio.com/gallery/widget-gallery.html)
- Web: [Shiny from RStudio](https://shiny.rstudio.com/)
- Web: [RStudio tutorials on Shiny](https://shiny.rstudio.com/tutorial/)
- Video: [Playlist: Web Apps in R: Building your First Web Application in R | Shiny Tutorial](https://www.youtube.com/watch?v=tfN10IUX9Lo&list=PLtqF5YXg7GLkxx_GGXDI_EiAvkhY9olbe)
- Example: [nnvizRt](https://leonjessen.shinyapps.io/nnvizRt/)
- More inspiration: [Shiny Gallery](https://shiny.rstudio.com/gallery/)
_Unless explicitly stated, do not do the per-chapter exercises in the R4DS2e book_
## Learning Objectives
_A student who has met the objectives of the session will be able to:_
- Prepare a simple shiny application
- Using relevant online resources to autonomously identify and obtain new and expand on existing knowledge of R
## Exercises {#sec-exercises}
### Introduction
----
In today's lab, you will use the package you developed last time as basis for a Shiny App.
Do not worry if you didn't finish it, you will be able to install a backup. But please do try to use your own package first.
You will be using the `golem` production-grade app development framework, which has a bit of a learning curve, but it is a solid starting point.
Please hang tight, as I walk you through how to get started.
When building a Shiny App with `golem`, you need everything you learned about creating an R package, because a `golem` Shiny App *is* a package, and all the same rules apply.
### TASKS
### Task 1 - Setting up the Shiny App
----
As last week, the first tasks are only done by **one team member**, until instructed otherwise.
Let the other team members follow along with what you are doing and do the following:
#### Task 1.1 - Create the App
1. Go to [R for Bio Data Science RStudio Server](https://teaching.healthtech.dtu.dk/22100/rstudio.php) and login.
2. Create a folder in home called `ShinyApps` - You need this for the server to find your app.
3. Run `golem::create_golem("~/ShinyApps/YOUR_APP_NAME")` in the console, putting in a name of your own choosing.
- As last week, the theme is the central dogma of molecular biology. Let that inspire you
- Look up naming rules [here](https://r-pkgs.org/workflow101.html#name-your-package)
- The most important rule: `_`, `-`, and `'` are not allowed.
4. Run `usethis::use_git()` to ensure git is initialized.
#### Task 1.2 - Make a GitHub repository for your group's app
1. Go to [https://github.com/rforbiodatascience24](https://github.com/rforbiodatascience24)
2. Click the green `New` button
3. Create a new repository called `group_X_shiny`. Remember to replace the **X**
4. Select `rforbiodatascience24` as owner
5. Make the repository `Public`
6. Click the green `Create repository` button
7. In this new repository, click the `settings` tab
8. Click `Collaborators and Team`
9. Click the green `Add people` button
10. Invite the remaining group members
11. All other team members should now have access to the repository, **but do not create your own project yet.**
#### Task 1.3 - Connect your RStudio Project to the GitHub Repository
**Still only the first team member**
1. Find your `PAT` key or create a new
<details> <summary>How to create a new one</summary>
<ul>
<li>Type in the console `usethis::create_github_token()`. You’re going to be redirected to GitHub website.
<li> In case you do it manually, remember to give permission to access your repositories.
<li>You need to type your password. Don’t change the default settings of creating the token except for the description – set ‘RStudio Server’ or something similar. Then hit Generate token.
<li>Copy the generated token (should start with ghp_) and store it securely (e.g. in password manager). Do not keep it in a plain file.
</ul></details>
2. Go back to the RStudio Server project.
3. Type in the console `gitcreds::gitcreds_set()` and paste the `PAT` key.
4. If there are files in the `git` window, stage them by ticking all boxes under `Staged`.
5. Still in the console, run the following commands. Replace your group number and use your GitHub username and email. You run these to link your project to the GitHub repository you created. Remember to replace the **X**.
```{r}
#| eval: false
usethis::use_git_remote(name = "origin", "https://github.com/rforbiodatascience24/group_X_shiny.git", overwrite = TRUE)
usethis::use_git_config(user.name = "USERNAME", user.email = "[email protected]")
gert::git_commit_all("App setup") # Only run if there were files to stage
gert::git_push("origin")
```
**All other team members**
*After your teammate has pushed to GitHub.*
1. You also need to create a `ShinyApps` folder.
2. In the RStudio Server, create a new project based on the GitHub Repository just created by your teammate.
- Click `Create a project`![](images/L08_create.png){width="5%"} in the top left.
- Choose `Version Control` and then `Git`.
- Paste in the repository URL: `https://github.com/rforbiodatascience24/group_X_shiny.git`. Remember to replace the **X**.
- Make sure to put it in the `ShinyApps` folder.
- Give the directory a fitting name and click `Create Project`.
2. Find your `PAT` key or create a new
<details> <summary>How to create a new one</summary>
<ul>
<li>Type in the console `usethis::create_github_token()`. You’re going to be redirected to GitHub website.
<li> In case you did it manually, remember to give permission to access your repositories.
<li>You need to type your password. Don’t change the default settings of creating the token except for the description – set ‘RStudio Server’ or something similar. Then hit Generate token.
<li>Copy the generated token (should start with ghp_) and store it securely (e.g. in password manager). Do not keep it in a plain file.
</ul></details>
3. Go back to the RStudio Server project
4. Type in the console `gitcreds::gitcreds_set()` and paste the `PAT` key
5. Still in the console, run the following commands. Replace your GitHub username and email.
```{r}
#| eval: false
usethis::use_git_config(user.name = "USERNAME", user.email = "[email protected]")
```
**If RStudio at any point asks you to log in to GitHub, redo step 6 and 7.**
### Task 2 - Create a production-grade Shiny app
----
It may seem daunting, but `golem` holds your hand much of the way.
#### Task 2.1 - The dev folder
`golem` creates a `dev` folder in your project. The files there are extremely helpful and you should make yourself familiar with the content. Read [this short chapter](https://engineering-shiny.org/setting-up-for-success.html#setting-up-for-success) to get a feeling for what each helper function does.
Also take a look at the [golem cheatsheet](https://raw.githubusercontent.com/rstudio/cheatsheets/main/golem.pdf).
1. Go through `dev/01_start.R` and run the setup functions you think will be useful. *Not everything is.*
- Run them in order. **Don't run line 36**, and if you are prompted to install packages, please decline.
- Everything on and above line 42 is recommended, everything else is optional. Feel free to see what they do. None of them should cause problems.
- After running the function for modifying the `DESCRIPTION` file, add more authors to the `DESCRIPTION` file using this layout:
```{r}
#| eval: false
Authors@R:
c(person(given = "firstname",
family = "lastname",
role = c("aut", "cre"), # There must be a "cre", but there can only be one
email = "[email protected]"),
person(given = "firstname",
family = "lastname",
role = "aut",
email = "[email protected]"))
```
2. Go through `dev/02_dev.R` to get an idea of what helper functions are available. You will likely use some of these functions quite frequently.
3. Look through `dev/03_deploy.R` to get an idea of how to deploy your app either in `shinapps.io`, as the app I showed in class, or on CRAN.
- Because we are operating on a server, we cannot run the app directly in our R session. Therefore, we should prepare the app for deployment. This will allow the shiny server hosted on the Health Tech Server to launch your apps.
- Run line 32 in `dev/03_deploy.R`, i.e., `golem::add_shinyserver_file()`
4. Look through `dev/run_dev.R` and run the first four commands. If you were not on a server, you could launch your app by running the last command `run_app()`. However, we *are* on a server, so we have implemented a small trick.
- When you ran line 32 previously, an `app.R` file was created. This allows the Health Tech Server to run your Shiny app from this url: `https://teaching.healthtech.dtu.dk/shiny/username/app_name/` - Edit username and app_name appropriately.
- You should see an empty app with your title. Now you just need to put stuff in it.
- **OBS** Sometimes, for unknown reasons, the browser removes the "shiny" part of the url. If you get a "Not Found" error, check the url.
- **Another OBS** For changes to take effect, you will have to close the app session, which means either closing the tab or removing the app name from the url. The latter will list all apps you have created - likely just this one so far. The url would then look like: `https://teaching.healthtech.dtu.dk/shiny/username/`.
#### The R folder
`golem` sets up a framework for your Shiny app.
This framework is probably a little different from what you normally see when reading/watching guides on Shiny Apps.
It may look overly complicated, and perhaps it is for this exercise. But it is a robust framework that makes maintaining even large apps easy(ier). Building a small app is very easy as well.
You are welcome to ignore the `R/run_app.R` (a wrapper function for `shiny::shinyApp()`, which runs the app) and `R/app_config.R` (some `golem` configuration) for now.
The first places you want to look are `R/app_ui.R` and `R/app_server.R`. They are responsible for the user interface and the app back end, respectively.
You will not be working here directly as much, although you could. But it is strongly recommended to work in Shiny modules - created with `golem::add_module( name = "module_name" )`, as you saw in class.
##### Shiny Modules
Shiny modules may appear to make your life more complicated at first, but they will save you a lot of time down the road - especially from bug-fixing and GitHub merging issues.
After creating a module, its `ui` and `server` functions should be copied into the `app_ui.R` and `app_server.R` scripts, as you will be reminded in the bottom of the module scripts.
There, you can control how the module should interact with the main app - should each module have their own tab in the app or should they be called depending on which button the user clicks on.
Another useful feature of Shiny modules is that you can test them independently from the main app.
I suggest, each time you create a module, to copy something like the following in the bottom of the created module script (renaming the relevant parts to fit the module). This way you always have a quick test environment at hand. But bear in mind the layout will be different from your main app, as it will not transfer the layout from `app_ui.R`.
```{r, eval=FALSE, echo=TRUE}
if(FALSE){ # Testing
golem::detach_all_attached()
golem::document_and_reload()
ui <- mod_NAME_ui("NAME_ui_1") # replace NAME here
server <- function( input,output,session){
mod_NAME_server("NAME_ui_1") # and here
}
shiny::shinyApp(ui, server)
}
```
If you want to learn how to make the modules share information, please read [here](https://engineering-shiny.org/structuring-project.html#communication-between-modules). I personally prefer approach B.
This is **not** necessary for the exercises, but I wanted to make you aware that it is possible. Feel free to use it in the Group Assignment.
### Task 3 - Populate your Shiny App
----
Last week, you created a package that simulates the central dogma of molecular biology.
Today, you will use that package to create an app around it.
**Please work together on these tasks.**
#### Task 3.1 - Install the package you created last week
1. `devtools::install_github("rforbiodatascience24/group_X_package")`. Remember to replace the **X**
<details><summary> Install backup </summary>
**Please only use this if your own package does not work!**
Install it with: `devtools::install_github("r4bds/centralDogma")`
The function names are as follows:
- Function one: `centralDogma::random_dna()`
- Function two: `centralDogma::transcribe()`
- Function three: `centralDogma::codon_split()`
- Function four: `centralDogma::translate()`
- Function five: `centralDogma::plot_abundance()`
</details>
You have already done the initial setup steps, so let's get started with building the app!
#### Task 3.2 - Design your primary layout
Feel free to use your imagination. Otherwise, follow my suggestion for a `tabsetPanel` layout:
If you make your own layout, make space for the two modules, as I did with the two tabPanels with temporary titles and module names below.
1. Add a `tabsetPanel` with 2 panels in the `fluidPage()` function within the `app_ui` function definition in `R/app_ui.R`. The `tabsetPanel` should be inserted after the header (written as h1(“header”) ), separated by a comma.
```{r}
#| eval: false
tabsetPanel(
tabPanel(title = "panel1",
"module1"),
tabPanel(title = "panel2",
"module2")
)
```
I have added placeholder names, you should replace these with relevant module functions as the app is build.
You will start by implementing the plotting module ("module2") because it is a lot simpler, with only a single text input and a plot.
#### Task 3.3 - Create the plotting shiny module
Your plotting module should take in a peptide sequence and plot the relative absolute abundance of each amino acid.
1. Go to `dev/02_dev.R` and find the function to add a module. For now, set `with_test = FALSE` - you will not be creating tests for the app in this exercise, unless you want to. Remember to name the module something sensible related to the description above instead of just "module2". Run the function.
2. Scroll to the bottom of the module and copy the commented out server function and add it to `R/app_server.R` inside the `app_server` function.
3. Redo step 2, but for the ui function. Importantly, place it in the second `tabPanel` in `R/app_ui.R`, instead of the "module2". Give it a sensible title. If you made your own layout, place the module where you imagine it should go.
4. **Go back to the module script**. Use my suggested module layout below. If you want, you are more than welcome to design it yourself. See the layout guide [here](https://shiny.posit.co/r/articles/build/layout-guide/) or [cheat sheet](https://rstudio.github.io/cheatsheets/html/shiny.html) for inspiration.
- Fill your desired layout in the `tagsList` of the `ui` function in the module.
<details> <summary>If you want, draw inspiration for the layout I chose </summary>
```{r}
#| eval: false
sidebarLayout(
sidebarPanel(
"peptide_sequence"
),
mainPanel(
"plot"
)
)
```
The names in the example are not actual shiny stuff, just names I put in as a placeholder. Feel free to use them as your inputIDs and outputIDs or come up with your own.
</details>
</br>
5. Run the app to see what it looks like (by refreshing the app url you created on Task 2.1).
- Remember if you get a "Not Found" error, the "/shiny/" might be missing from the url.
6. Add an input field for the `peptide_sequence`, replace the string with the input you are adding. Please try it out first.
- Remember `ns()` around input/output IDs
<details> <summary>Possible solution </summary>
```{r}
#| eval: false
textAreaInput(
inputId = ns("peptide"),
label = "Peptide sequence",
width = 300,
height = 100,
placeholder = "Insert peptide sequence"
)
```
</details>
</br>
7. Add an output field for the `plot`, replacing the placeholder string. Please try it out first.
<details> <summary>Possible solution </summary>
```{r}
#| eval: false
plotOutput(
outputId = ns("abundance")
)
```
</details>
<details> <summary>Full possible solution </summary>
```{r}
#| eval: false
mod_abundance_ui <- function(id){
ns <- NS(id)
tagList(
shiny::sidebarLayout(
shiny::sidebarPanel(
shiny::textAreaInput(
inputId = ns("peptide"),
label = "Peptide sequence",
width = 300,
height = 100,
placeholder = "Insert peptide sequence"
)
),
shiny::mainPanel(
shiny::plotOutput(
outputId = ns("abundance")
)
)
)
)
}
```
</details>
#### Task 3.4 - Plotting module server logic
<!-- There should be something that handles the peptide sequence and something that gives that sequence to a plotting function, whose output should be displayed in the app.
-->
There are several ways to solve this task, but keep in mind that if an empty string is given to `function_five`, it will give an error and the app will crash. Prevent that.
Please try to make the server logic on your own. Also feel free to add an additional button to control when the plotting is happening (see my slide on reactivity for inspiration).
1. **Go the the module server function.** Make the server logic for handling the text input and render a plot using `function_five` from your package, remember to rename the function call appropriately (`yourpackage::function_five`).
- Ensure the IDs match.
- It does not matter where in the module server function you put it, as long as you put it inside the function.
<details> <summary>Possible solution </summary>
```{r}
#| eval: false
output$abundance <- renderPlot({
if(input$peptide == ""){
NULL
} else{
input$peptide |>
yourpackage::function_five() +
ggplot2::theme(legend.position = "none")
}
})
```
</details>
</br>
2. **Discuss in your group what is going on in my solution**. Why does it work, and what other ways could you get to the same solution (check my slide on reactivity for inspiration). As a small note, I chose to hide the legend, as that looked better in the app.
3. Add `@importFrom ggplot2 theme` and `@import yourpackage` to the module server function description.
4. Go to `dev/02_dev.R` and run the first function to add `ggplot2` and `yourpackage` to your package dependencies: `attachment::att_amend_desc()`. Or add it to the `DESCRIPTION` manually.
5. Run every line but the last in `dev/run_dev.R` and reopen your app to see that it works (You can just type in random amino acids in the field).
- If you run the last line, a popup will tell you the connection is refused - it would work locally, but doesn't on the server.
- Remember if you get a "Not Found" error, the "/shiny/" might be missing from the url.
- If no changes appear, close the tab for a minute and try again.
#### Task 3.5 - Create shiny "module1"
The "module1" module (please pick a sensible name) should take in a DNA strand and convert it into a peptide sequence.
There should also be an option to create a random DNA strand, in case the user does not have one of their own.
1. Go to `dev/02_dev.R` and find the function to add a module. Again, set `with_test = FALSE`. Remember to name the module something sensible related to the description above. Run the function.
2. In the created module file, scroll to the bottom of the module and copy the commented out module server function and add it to `R/app_server.R` in the `app_server` function.
3. Do the same for the ui function. Importantly, place it in the first `tabPanel` in `R/app_ui.R`, replacing the "module1" string. Give it a sensible title. If you made your own layout, place the module where you imagine it should go.
4. Go back to the module script. Use my suggested module layout below. If you want, you are more than welcome to design it yourself. See the layout guide [here](https://shiny.posit.co/r/articles/build/layout-guide/) or [cheat sheet](https://rstudio.github.io/cheatsheets/html/shiny.html) for inspiration.
- Fill your desired layout in the `tagsList` of the `ui` function in the module.
```{r}
#| eval: false
fluidRow(
column(8, "DNA_sequence"),
column(4, "random_dna_length", "generate_dna_button")
),
"peptide_sequence"
```
Again, the names in the example are not actual shiny stuff, just names I put in as a placeholder. Feel free to use them as your inputIDs and outputIDs or come up with your own.
5. Before we continue, try to run the app: Run every line but the last in `dev/run_dev.R` and reopen your app.
- Remember if you get a "Not Found" error, the "/shiny/" might be missing from the URL.
- If no changes appear, close the tab for a minute and try again.
6. **Discuss in your group which parts of the UI needs to be reactive (updateable) and which don't.** Of course, when you type a letter, the letter should appear where you typed it - that part happens automatically. But what needs to update when a button is clicked or an input changes?
7. Let's add some inputs (buttons, text, etc.):
- Go [here](https://shiny.posit.co/r/gallery/widgets/widget-gallery/) for inspiration for inputs.
- Look at the shiny [cheat sheet](https://rstudio.github.io/cheatsheets/html/shiny.html) for inspiration for input and output.
- Remember to wrap your input/output IDs with `ns()` (required in modules).
<details> <summary>Hint for `DNA_sequence` </summary>
For the DNA input, I wanted the sequence to be updated when the user clicks the "generate_dna_button" button. The simplest way to make UI inputs reactive is with an `uiOutput()`. My "DNA_sequence" look like: `uiOutput(ns("DNA"))`. The content of the field will be defined in the server.
</details>
<details> <summary>Hint for `random_dna_length` and `generate_dna_button` </summary>
I chose a numeric input for the "random_dna_length" and an actionButton for the "generate_dna_button". They look like:
```{r}
#| eval: false
numericInput(
inputId = ns("dna_length"),
value = 6000,
min = 3,
max = 100000,
step = 3,
label = "Random DNA length"
),
actionButton(
inputId = ns("generate_dna"),
label = "Generate random DNA", style = "margin-top: 18px;"
)
```
I added the style to adjust the position of the button. That is in no way required.
</details>
<details> <summary>Hint for `peptide_sequence` </summary>
For "peptide_sequence", I chose a `verbatimTextOutput`. You may not have seen it before; it is in the shiny cheat sheet, but it simply allows for long-form text output in a grey box.
The `tagAppendAttributes` allow you to add CSS tags (you don't need to know what that means). In this case, I wanted the text to wrap. By googling a bit, I found the solution seen below (feel free to see how it looks with and without it - but remember you will first see something, when you have made the server logic in the next task).
```{r}
#| eval: false
verbatimTextOutput(outputId = ns("peptide")) |>
tagAppendAttributes(style = "white-space: pre-wrap;")
```
</details>
<details> <summary>Full possible solution</summary>
```{r}
#| eval: false
mod_dna_expression_ui <- function(id){
ns <- NS(id)
tagList(
fluidRow(
column(8, shiny::uiOutput(ns("DNA"))),
column(4, shiny::numericInput(
inputId = ns("dna_length"),
value = 6000,
min = 3,
max = 100000,
step = 3,
label = "Random DNA length"
),
shiny::actionButton(
inputId = ns("generate_dna"),
label = "Generate random DNA", style = "margin-top: 18px;"
))
),
shiny::verbatimTextOutput(outputId = ns("peptide")) |>
shiny::tagAppendAttributes(style = "white-space: pre-wrap;")
)
}
```
</details>
</br>
8. Reopen your app to see what it looks like. Remember, all `output` stuff will not appear before the server outputs something to it.
#### Task 3.6 - Adding server logic
This task might seem a bit confusing, but hang tight!
Let me take you through this one step at a time.
1. First, the DNA sequence should be an object that reacts to user input. Therefore, it should be a reactive value.
- As the first line to add in the server function in your module, write `dna <- reactiveVal()`.
- Read more about reactive values [here](https://mastering-shiny.org/reactivity-objects.html?q=reactiveVal#reactive-values) if you like. The important thing to have in mind is that every time you want to get the value run `dna()`, and when you update it run `dna(new_value)` with your new value - you will see an example of this in a minute.
2. If you, like me, wanted your DNA input strand to be updateable in the input field, add the following somewhere in the server:
```{r}
#| eval: false
output$DNA <- renderUI({
textAreaInput(
inputId = ns("DNA"),
label = "DNA sequence",
placeholder = "Insert DNA sequence",
value = dna(),
height = 100,
width = 600
)
})
```
- Make sure the IDs match.
- **Discuss in the group what is going on there.**
<details> <summary>Answer </summary>
The `output$DNA` informs shiny to update the output with DNA as ID from the UI. In this case the `uiOutput` you added earlier.
The `renderUI` creates a UI field. This function is complementary to the `uiOutput`.
`textAreaInput` is a large text input field - suitable for large text inputs, such as DNA.
The `ns()` should always be called when adding input/output fields in modules. Note that it is not necessary when assigning to outputs, such as `output$DNA`.
The `dna()` adds the DNA strand as the value in the field, this ensures that the updated DNA value is displayed in the input field, when it is generated with the 'random DNA' function.
As an added note, notice that the input and output IDs can be the same, as with the `ns("DNA")` ID for both `uiOutput` and `textAreaInput` in this case. I find it handy to name them the same, so I know which input and output interacts. If you find it confusing, you can name them something else.
</details>
</br>
3. The next step is to add a reaction when the "generate random DNA" button is clicked.
- There are a few ways to handle this. My favorite is the following:
```{r}
#| eval: false
observeEvent(input$generate_dna, {
dna(
yourpackage::function_one(input$dna_length)
)
})
```
4. Write the name of your package instead of `yourpackage` and add the name you gave function one from last week's exercise.
- Make sure the input names are the same as for your app (`generate_dna` and `dna_length`)
- **Discuss in your group what is going on.** Before looking at the answer, consider reading [this section](https://mastering-shiny.org/basic-reactivity.html?q=observ#observers).
<details> <summary>Answer </summary>
The `observeEvent` function observes when a change occurs to the `generate_dna` input.
The reaction to a change then involves updating the dna value to the output of `function_one()` - or what you chose to call the function.
</details>
</br>
5. Lastly, we should address what happens when there is DNA to be translated into a peptide:
- Feel free to play around with a solution, based on what you have done previously.
- The challenging part is to make the peptide update automatically without initial loading problems or nuisance for the user (the latter refers to a problem where an [observer](https://mastering-shiny.org/basic-reactivity.html?q=observer#observers) may deselect the text input field such that the user has to press the field again to continue typing.)
- Otherwise, use my solution below:
<details> <summary>Possible solution </summary>
This may not work as intended if you did not choose the `uiOutput` for the DNA input field. Then you may have to use `dna()` or add an `actionButton`. Ask if you run into issues. Please note that I am using `input$DNA` and *not* `dna()`. You will discuss why in a minute, but feel free to try it out both ways and see if you notice the difference.
```{r}
#| eval: false
output$peptide <- renderText({
# Ensure input is not NULL and is longer than 2 characters
if(is.null(input$DNA)){
NULL
} else if(nchar(input$DNA) < 3){
NULL
} else{
input$DNA |>
toupper() |>
yourpackage::function_two() |>
yourpackage::function_three() |>
yourpackage::function_four()
}
})
```
</details>
</br>
6. Regardless of wether you used my solution or not, **discuss in your group what goes on in my solution**
<details> <summary>Answer </summary>
With a direct `renderText` on the `input$DNA`, the output will update whenever the input field changes, without causing the nuisance described above, which would be introduced with an `observeEvent` without an associated `actionButton`. Recall `input$DNA` gets updated when `generate_dna` is clicked.
The first test checks that the input is not `NULL`, which it is upon loading the app, causing an error message in the console, but doesn't necessarily crash the app. An output of `NULL` renders nothing (this fact can be useful when building apps in the future).
The second test ensures an output is only generated when there is more than 3 characters to interpret.
The `toupper()` function ensures the input is upper case, which is required for the codon table.
`renderText` does as you would expect and renders some text for the UI. You might have guessed from the row of functions in the `renderText`, it takes the dna strand and converts it using the package you created last week into a peptide sequence.
This peptide sequence is then stored in the peptide output, which links to the `verbatimTextOutput` you likely have in your ui function
</details>
</br>
7. Please make sure all input and output IDs match in the UI and Server functions.
8. Go to `dev/02_dev.R` and run the first function to add dependencies: `attachment::att_amend_desc()` or do it manually.
9. Reopen the app and see if it acts as expected.
- Remember if you get a "Not Found" error, the "/shiny/" might be missing from the url.
- If no changes appear, close the tab for a minute and try again.
10. Push it to GitHub
</br>
Awesomely done! You have now created a fully functional R shiny application that takes in a DNA strand or creates a random one, converts it into a peptide sequence, and then is able to plot the abundance of each amino acid in the sequence.
## <span style="color: red;">GROUP ASSIGNMENT</span>
----
This week's assignment is a short group discussion (1/4 - 1/2 page).
Please cover these topics:
- What did you find most challenging about creating a shiny app?
- What do you feel are the benefits and challenges with using `golem` for app development?
- Maintaining reproducibility when using shiny apps is a challenge. As an example, some pharma-companies display databases to medical doctors for pointy-clicky data exploration. What are your thoughts on maintaining reproducibility in that scenario? What if the database is updated or the app is updated with new or changed functionality?
- What other challenges and limitations do you see shiny apps may have? Please elaborate.
- Hand in a pdf with you discussion points and links to your shiny app GitHub page and the app itself.
As an **optional** extra challenge, try to expand your shiny app with a third module.
You decide what the content of the module should be. Remember to put the shiny module functions somewhere in `R/app_ui.R` in the `app_ui` function and `R/app_server.R` in the `app_server` function.
If you made one, add a brief description of the module in the hand-in.