forked from WCSCourses/Helminths_2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial1.Rmd
More file actions
575 lines (276 loc) · 14.1 KB
/
Copy pathtutorial1.Rmd
File metadata and controls
575 lines (276 loc) · 14.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
---
title: 'R with R studio: An introduction '
author: "Jason Tsai and Steve Doyle"
date: "09/06/2021"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
#install.packages("rmarkdown")
#devtools::install_github("hadley/emo")
#install.packages("knitr")
#install.packages("tidyverse")
#install.packages("nycflights13")
#library("nycflights13")
#library("emo")
```
## Overview and aims
> “The simple graph has brought more information to the data analyst’s mind than any other device.”
— John Tukey
The goal for this module is to help you to learn the basics in R so you can go away and start to tackle your own data. R is aprogramming language which its first version launched back in 2000. There are many reasons to use R:
* easy to use and has excellent graphic capabilities
* it has lots of new statistical methods to be used in a straightforward manner
* it's **open source** and **free**.
* because of ⬆️ ,it is supported by a large user network.
* because of ⬆️⬆️, it has lots and lots of new analysis packages
* it is also old, but because of ⬆️⬆️⬆️, you can use the more intuitive new functions which does things much faster.
* it can be run on Windows, Linux and Mac
Within the research discipline, what most people think of data analysis they think of the following below - turn data from excel to some shiny figures that are presentable.

There is now the exciting research discipline of Data science that allows you to "turn raw data into understanding, insight and knowledge". In this lectures, we will use a lot of materials from the book **R for Data Science** written by Hadley Wickham and Garrett Grolemund (will now be referred as R4DS. https://r4ds.had.co.nz/ ) but tailored to helminth related data. This book is designed for absolute beginners to learn all the basics of R. It is free online and should be encouraged to read further after these lectures.
The goal of data analysis is to explore, gain insights and interpret your data. A analysis cycle usually looks something like this:
![Concept of a Program from [R4DS] ](https://d33wubrfki0l68.cloudfront.net/571b056757d68e6df81a3e3853f54d3c76ad6efc/32d37/diagrams/data-science.png)
setting up R and environment
Basics of R
importing / exporing data
manipulating / tidying data
visualising data
All the lectures
[R4DS]: https://r4ds.had.co.nz/introduction.html "R for Data Science"
## Day 1: Introduction
Now let's double click on R studio from your VM.
A screenshot of R studio, which is split into Console, the script and want
Let's click on the Console. You should be able to do some calculations from
### R as a calculator
```{r eval=FALSE}
# everything after the hash '#' symbol will be a comment and not actual code
# same here
# and here..
#Press enter to complete the expression
# We are going to do 2 plus 3
2+3
# multiplications
2*3
# divide
2/3
# By simply pressing return/enter, you get a complete expression
1
#Incomplete expression will result in continuation prompt +
3+
1111+
1000
```
Simple 😎 , isn't it?
### Assignment operator
The calculations will be meaningless if we don't store them for later use. So we will use the assignment operator **<-** to create new variables.
```{r eval=FALSE}
# <- is the assignment operator
# We will assign 5 to x
x<- 5
# assign 10 to y
y <- 10
# To check if the assignments are successful,
# you can always simply type x or y and press return
x
y
# R is case sensitive
# x does not equal to X
X <- 10
# Original value of 5 in x is replaced with 10
x<- 10
# New value can be assigned as the result of calculation
z <- x + y + X
z
# try a few things yourself
```
### R data structure
In order to start appreciating the powerfulness of R, the data needs to be organised in such a way, i.e., tidied so calculations can be used performed on them. There are many data type and structures in R. For simplicity we will introduce only two data structures: **vector** and **data frame**, and two data types: **nucmeric** and **character** (text based).
Vector is the simplest data structure in R. It essentially contains a series of values of the same type. Data frames are a collection of vectors in columns. think of it like Excel spreadsheets. And each row represents a sample. To iterate:
Rows represent samples
E.g., sample A in Row 1, sample B
And all the values of the same variable must go in the same column
E.g., age, sex, RPKM, numbers
We note here that there are newer and more intuitive ways of manipulation of data frame-type data, and we will use `tibble` from the `dplyr` package later in the module.

```{r eval=FALSE}
#Assign a vector of 1 to 10 to x
#c means combine or concatenate
x<- c(1,2,3,4,5,6,7,8,9,10)
# Now we can do calculations on all the values within a vector at once!
x *2
x / 10 + 1
```
### Functions
Note in previous code block we actually introduced a **function** `c`, and there are many built-in functions in R that are waiting to be discovered! A function is applied using **round brackets** , and can take **arguments** and **options**.
`function (arg1, arg2, arg3… , option1=,option2=...)`
```{r eval=FALSE}
# let's make x
x<- c(1,2,3,4,5,6,7,8,9,10)
# In fact, same thing can be achieved with the function seq
x<- seq(1,10)
# Adding an option by = 2 in the seq function
# What does it do?
x <- seq(1,10, by= 2)
# if you would like to view what options a particular function has,
# add ? in front of the function and press enter
?seq
# try out all these functions to see what they produce!
length(x)
mean(x)
mean(y)
median(x)
max(x)
```
We end today's session with a `plot` function.
```{r eval=FALSE}
# We now set two vectors of 10 numbers
x<- c(1,2,3,4,5,6,7,8,9,10)
y<- c(3,6,9,10,13,30,20,100,220,100)
# Simple plot x and y for their relationship
# Note each set of numbers will be paired according to their orders
# So first number in x is 1 and will be paired with 3 in y.
plot(x,y)
# plot has a option col
plot(x,y,col="red")
# many functions have additional parameters
boxplot(x,y,col="red")
# I like hotpink
boxplot(x,y,col=c("hotpink", "yellow") )
boxplot(x,y,col=c("hotpink", "yellow"), main="Your first plot" )
# can use the ? sign to find out more about function
?boxplot
```
### Summary
We now end with first R lecture.
## Day 2: Data Wrangling
In today's lecture we start with data wrangling, which is a term used in data science of getting your raw data to such a format that can be used in R for further analysis and visualisation. Raw data is often very messy, which requires some sort of manipulations. In the old days we usually copied and pasted from different excel spreadsheets. But if new data arrives the whole manual process is repeated again, which is time consuming and may lead to human caused errors.
Today you will see that a lot of actions can be done with existing **functions** in R.
![Data Wragling [R4DS] ](https://d33wubrfki0l68.cloudfront.net/e3f9e555d0035731c04642ceb58a03fb84b98a7d/4f070/diagrams/data-science-wrangle.png){width=50%, height=50%}
### Packages
R consists of a **core** and **additional** packages. They are collections of R functions, data, and compiled code, with well-defined format that ensures easy installation, a basic standard of documentation, and enhances portability and reliability.
Here we will use the `tidyverse` package, which is highly recommended for manipulating data strcutre.
```{r package, message=FALSE, warning=FALSE}
# the function of of installing packages
# The tidyverse package is already installed in VM, so we will comment out here
# install.packages("tidyverse")
#after it’s installed, you can initiate by using library
library(tidyverse)
```
### Data import
**Steve here**
In this exercise, we will be using data downloaded the Global Atlas of Helminth Infection (GAHI; http://www.thiswormyworld.org ). There will be three files which are available to download at
* `Ascaris_prevalence.txt`
* `Hookworms prevalence.txt`
* `Schisoma_mansoni_prevalence.txt`
They are text files where each column of data is separated by **tab**, i.e., a **tab delimiter**. This allows R to know how data is separated. In the future
Now we are going to read the `Ascaris_prevalence.txt` file into R using the `read_delim` function in R. We need to tell R that is it tab delimited. Once it's read successfully, the file will be a `tibble` format, which allows a lot of nice functions to act on it.
```{r read_delim, message=FALSE,}
ascaris <- read_delim(file = "Ascaris_prevalence.txt", delim ="\t")
# Success! You should have read some messages!
# Now ascaris is a tibble
ascaris
# What columns does the table have?
colnames(ascaris)
```
### Data tranformation
From R4DS.
In this section, you are going to learn the five key `dplyr` functions that allow you to solve the vast majority of your data manipulation challenges:
* Pick observations by their values (`filter()`).
* Reorder the rows (`arrange()`).
* Pick variables by their names (`select()`).
* Create new variables with functions of existing variables (`mutate()`).
* Collapse many values down to a single summary (`summarise()`).
These can all be used in conjunction with `group_by()` which changes the scope of each function from operating on the entire dataset to operating on it group-by-group. These six functions provide the verbs for a language of data manipulation.
#### Filtering
`filter()` allows you to subset observations based on their values. The first argument is the name of the data frame. The second and subsequent arguments are the expressions that filter the tibble.

```{r}
# Let's filter based on region Africa
filter(ascaris, Region == "Africa")
# Note the previous command only display the output,
# which is normal when you are trying to explore different functions and options
# In order to save the output, you need to save into a new tibble
ascaris.africa <- filter(ascaris, Region == "Africa")
ascaris.africa
# try a few things yourselves
ascaris.angola <- filter(ascaris, Country == "Angola")
ascaris.angola
```
#### Mutate
Besides selecting sets of existing columns, it’s often useful to add new columns that are functions of existing columns. That’s the job of `mutate()`.
mutate() always adds new columns at the end of your dataset so we’ll start by creating a narrower dataset so we can see the new variables. Remember that when you’re in RStudio, the easiest way to see all the columns is View().

```{r}
ascaris <- mutate(ascaris, Prevalence = No.positives / No.indiv.surveyed )
```
#### Arrange
`arrange()` works similarly to `filter()` except that instead of selecting rows, it changes their order. It takes a data frame and a set of column names (or more complicated expressions) to order by. If you provide more than one column name, each additional column will be used to break ties in the values of preceding columns:

```{r}
arrange(ascaris, Prevalence)
#Use desc() to re-order by a column in descending order:
arrange(ascaris, desc(Prevalence))
arrange(ascaris, Country, Prevalence)
```
#### Select
It’s not uncommon to get datasets with hundreds or even thousands of variables. In this case, the first challenge is often narrowing in on the variables you’re actually interested in. `select()` allows you to rapidly zoom in on a useful subset using operations based on the names of the variables.

```{r}
select(ascaris,Country, Prevalence)
```
#### Group_by and Summarise
The last key verb is summarise(). It collapses a data frame to a single row.
Together `group_by()` and `summarise()` provide one of the tools that you’ll use most commonly when working with dplyr: grouped summaries. But before we go any further with this, we need to introduce a powerful new idea: the pipe.

```{r}
```

```{r}
```
#### Pipe
Imagine that we want to explore the relationship between the distance and average delay for each location. Using what you know about dplyr, you might write code like this
```{r}
ascaris %>%
select(Country, Prevalence) %>%
arrange(desc(Prevalence))
```
This focuses on the transformations, not what’s being transformed, which makes the code easier to read. You can read it as a series of imperative statements: group, then summarise, then filter. As suggested by this reading, a good way to pronounce %>% when reading code is “then”.
Working with the pipe is one of the key criteria for belonging to the tidyverse.
Now it seems that Philippines are quite high. Can we make a plot?
### Visusalisation
Boxplot
```{r}
ggplot(ascaris, aes(x = Country, y = Prevalence)) +
geom_boxplot(aes(fill=Country))
ggplot(ascaris, aes(x = reorder(Country,Prevalence), y = Prevalence)) +
geom_boxplot(aes(fill=Country))
ggplot(ascaris, aes(x = reorder(Country,-Prevalence), y = Prevalence)) +
geom_boxplot(aes(fill=Country))
ggplot(ascaris, aes(x = reorder(Country,-Prevalence), y = Prevalence)) +
geom_boxplot(aes(fill=Country)) +
theme(axis.text.x = element_text(angle = 45))
ggplot(ascaris, aes(x = reorder(Country,-Prevalence), y = Prevalence)) +
geom_boxplot(aes(fill=Country)) +
theme(axis.text.x = element_text(angle = 45, hjust=1))
```
#### Merge table
Finally.
```{r}
schisto <- read_delim(file = "Schisoma_mansoni_prevalence.txt", delim ="\t")
```
```{r}
ascaris <- add_column(ascaris, disease = "ascaris")
schisto <- add_column(schisto, disease = "schisto")
combined.tb <- union(ascaris,schisto)
ggplot(combined.tb, aes(x = reorder(Country,-Prevalence), y = Prevalence, fill=disease)) +
geom_boxplot() +
theme(axis.text.x = element_text(angle = 45, hjust=1))
```
```{r}
prevalence.by.country.and.disease <- combined.tb %>%
group_by(Country, disease) %>%
summarise( sites = n(),
total.ind = sum(No.indiv.surveyed),
total.positives = sum(No.positives),
average.Prevalence = mean(Prevalence) )
```
### Additional Exercises and reading