-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_vis.Rmd
351 lines (205 loc) · 10.7 KB
/
data_vis.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
---
title: "Data Visualisation"
output:
learnr::tutorial:
progressive: true
allow_skip: true
runtime: shiny_prerendered
description: >
Learn how to get started with R and RStudio, and how to import a dataset
---
<!-- Add JavaScript code for making the exercise code larger -->
<script language="JavaScript" src="js/exercise-font-size.js"></script>
```{r setup, include=FALSE}
# load packages ----------------------------------------------------------------
library(learnr)
library(gradethis)
library(tidyverse)
library(here)
library(rio)
library(basket) # not sure if we need this
library(etude) # helper functions for gradethis
# set options for exercises and checking ---------------------------------------
gradethis_setup()
learnr::tutorial_options(exercise.timelimit = 60)
#exercise.checker = gradethis::grade_learnr)
# alternatively, submitr::null_code_checker
# event recorder ---------------------------------------------------------------
# see https://github.com/dtkaplan/submitr/blob/master/R/make_a_recorder.R
tutorial_options(exercise.eval = FALSE) # pre-evaluate exercises
vfun <- submitr::make_basic_validator(NULL, "hello") #basket::check_valid
new_recorder <- function(tutorial_id, tutorial_version, user_id, event, data) {
cat(
tutorial_id,
" (v", tutorial_version, "); ",
format(Sys.time(), "%Y-%M%-%D %H:%M:%S %Z"), "; ",
user_id, "; ",
event, "; ",
data$label, "; ",
data$answers, "; ",
data$code, "; ",
data$correct, "\n", sep = "",
file = here::here("event_records", "learnr_basics.txt"),
append = TRUE)
}
options(tutorial.event_recorder = new_recorder)
# hide non-exercise code chunks ------------------------------------------------
knitr::opts_chunk$set(echo = FALSE)
# data prep --------------------------------------------------------------------
linelist_raw <- rio::import(here::here("data", "linelist_raw.xlsx"))
linelist <- rio::import(here::here("data", "linelist_cleaned.rds"))
malaria_counts <- rio::import(here::here("data", "malaria_facility_count_data.rds"))
```
```{r}
submitr::login_controls() # show login and password with "Submit" button.
```
```{r context = "server", echo = FALSE}
# see https://rdrr.io/github/dtkaplan/submitr/f/vignettes/using.Rmd
options(tutorial.storage = "none")
vfun <- submitr::make_basic_validator(NULL, "hello") #basket::check_valid
storage_actions <- submitr::record_local("./minimal_submissions.csv")
submitr::shiny_logic(input, output, session, vfun,
storage_actions)
```
## Introduction to R for Applied Epidemiology and Public Health
### Data visualisation
```{r appliedepi-banner, fig.margin = TRUE, echo = FALSE, fig.width = 3, out.width = "100%", fig.cap = ""}
knitr::include_graphics("images/moz-banner.png")
```
### Welcome
Welcome to the course "Introduction to R for applied epidemiologists", offered for free by [Applied Epi](www.appliedepi.org) - a non-profit organisation that offers open-source tools, training, and support to frontline public health practitioners.
This interactive tutorial focuses on **visualisation of data with the ggplot2 R package**, for example into figures such as epidemic curves, demographic pyramids, and many varieties of bar, line, and scatter plots.
This tutorial draws from chapters of our free [Epidemiologist R handbook](https://epirhandbook.com/en/) such as [ggplot basics](https://www.epirhandbook.com/en/ggplot-basics.html), [ggplot tips](https://www.epirhandbook.com/en/ggplot-tips.html), [epidemic curves](https://www.epirhandbook.com/en/epidemic-curves.html). The Epi R Handbook has over 50 chapters, has helped over 110,000 people learn R, and is also available for offline use.
#### Target Audience
This course is designed with the following objectives:
* To be friendly to people who have never used a programming language before
* To teach R emphasizing examples, datasets, and challenges commonly faced by applied epidemiologists
* To be modular - so that you can skip to section most relevant to you
We expect that you know how to do ... TO DO
#### Other languages
This course is available...
#### Offline / Online
You can access this tutorial offline by downloading our R package ...
If viewing offline, you can view the videos by doing ...
#### Learning goals
In this tutorial you will:
* Cleaning data useing the fundamental **tidyverse** R functions
* ...
* ...
#### Data consent
This tutorial is anonymously collecting your entries, for purposes of improvement... by Continuing you consent to this collection and use.
#### Who made this course
This course is designed by epidemiologists with decades of ground-level experience in outbreak response and local public health work.
```{r appliedepi-hexes, fig.margin = TRUE, echo = FALSE, fig.width = 3, out.width = "50%", fig.cap = ""}
knitr::include_graphics("images/hex-sidebyside.png")
```
## Data used and directory structure
In this tutorial we will use the following datasets. Please take a few minutes to review the structure and content of each dataset before continuing.
Use the arrows on the right to scroll through hidden columns. Note that these are "raw" (messy) datasets that mimic problems commonly found in real-life epidemiological datasets.
### **A "linelist" of cases in a fictional (not real) Ebola outbreak***
A "linelist" is a term used in applied epidemiology to refer to a table that contains key information about each case or suspect case in an outbreak. Each row represents one case, and the columns contain variables such as age, sex, date of symptom onset, outcomes, etc.
This dataset contains `r nrow(linelist_raw)` rows and `r ncol(linelist_raw)` columns. Below are the first 5 rows:
```{r}
head(linelist_raw)
```
Click to [download the **raw** dataset](https://github.com/appliedepi/epirhandbook_eng/raw/master/data/case_linelists/linelist_raw.xlsx) for your own practice.
Click to [download the **clean** dataset as an **.rds file**](https://github.com/appliedepi/epirhandbook_eng/raw/master/data/case_linelists/linelist_cleaned.rds) for your own practice. A *.rds file* is an R-specific file type that preserves column classes. This ensures you will have only minimal cleaning to do after importing the data into R.
### **Aggregated data from malaria surveillance in a fictional country**
Aggregated data in epidemiology usually means a table of counts for each facility, or district, etc. Sometimes, the counts can also be per day, week, or month.
In this fictional dataset, each facility reported *daily* case counts of rapid-test (RDT)-confirmed malaria. Thus, each row represents the number of cases for a specific facility on a specific day.
This dataset contains `r nrow(malaria_counts)` rows and `r ncol(malaria_counts)` columns. Below are the first 5 rows:
```{r}
head(malaria_counts)
```
Click to [download the **clean** malaria counts dataset as an **.rds file**](https://github.com/appliedepi/epirhandbook_eng/raw/master/data/malaria_facility_count_data.rds) for your own practice. A *.rds file* is an R-specific file type that preserves column classes. This ensures you will have only minimal cleaning to do after importing the data into R.
### Directory structure
Photo or GIF of directory structure
### Accessing example data
Here is how to access the example data
### Tidy Data
We highly recommend doing our tutorial on Tidy Data in Applied Epidemiology. Collecting, formatting, and preparing your dataset *before* importing it into R is a critical step!
LINK
VIDEO TEASER
## Install and Load R packages {#packages}
To use basic functions with public health data, the tidyverse metapackage is very useful. Tidyverse loads the dplyr, ggplot2, and other packages that are useful in epi data analysis.
We've preloaded the below packages for now. Installation and loading of these packages is described on the EpiRHandbook [_Suggested Packages_](https://epirhandbook.com/en/suggested-packages-1.html) page.
In this assignment we'll work with X R packages, let's load them!
```{r load-package, exercise = TRUE}
pacman::p_load(___)
```
```{r load-package-hint}
pacman::p_load(rio, here, janitor, tidyverse)
```
```{r load-package-check}
grade_this_code("You are correct, the packages you need for this lesson are now loaded!")
```
```{r eval= FALSE}
pacman::p_load(learnr, here, rio, janitor, tidyverse)
```
### Recommended R packages for public health
See this Epi R Handbook LINK for our recommended packages.
## Import data {#import}
Import that data and save it as "raw" file
To import data from a sub-folder, the `import()` command should be modified so that it correctly tells R where to search for this file. This is done using the here() function.
```{r import-demo-subfolder, echo=T, eval=F}
linelist_raw <- import(here("data", "linelist_raw.xlsx")) # import data and save as named object
```
## ggplot basics
### grammer of graphics
## Open the plot
## Map column to aesthetic features
## Add geoms
## Scales
### colors
### y-axis breaks
## Theme elements
## Facets
## Common epidemiological plots
### Epidemic cuves
### Bar plots
#### Horizontal
#### Labels
### Demographic pyramids
## Order (facets)
## Labels
### Dynamic labels
## Dual axes
## Data structure
### Pivoting
## Next steps
## TEMPLATE Exercises
### Exercise with Code
*Here's an exercise with some prepopulated code as well as `exercise.lines = 5` to provide a bit more initial room to work.*
Now write a function that adds any two numbers and then call it:
```{r add-function, exercise=TRUE, exercise.lines = 5}
add <- function() {
}
```
### Exercise with Hint
*Here's an exercise where the chunk is pre-evaulated via the `exercise.eval` option (so the user can see the default output we'd like them to customize). We also add a "hint" to the correct solution via the chunk immediate below labeled `print-limit-hint`.*
Modify the following code to limit the number of rows printed to 5:
```{r print-limit, exercise=TRUE, exercise.eval=TRUE}
mtcars
```
```{r print-limit-hint}
head(mtcars)
```
### Quiz
*You can include any number of single or multiple choice questions as a quiz. Use the `question` function to define a question and the `quiz` function for grouping multiple questions together.*
Some questions to verify that you understand the purposes of various base and recommended R packages:
```{r quiz}
quiz(
question("Which package contains functions for installing other R packages?",
answer("base"),
answer("tools"),
answer("utils", correct = TRUE),
answer("codetools")
),
question("Which of the R packages listed below are used to create plots?",
answer("lattice", correct = TRUE),
answer("tools"),
answer("stats"),
answer("grid", correct = TRUE)
)
)
```