forked from mvanrongen/2020-01-20_NST_Bioinformatics
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01-intro-to-r.Rmd
368 lines (282 loc) · 14.6 KB
/
01-intro-to-r.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
---
title: "Introduction to R"
---
```{r, echo = FALSE, purl = FALSE, message = FALSE}
source("setup.R")
knitr::opts_chunk$set(fig.path = paste0(knitr::opts_chunk$get("fig.path"),
"01-"))
surveys <- read_csv("data_raw/portal_data_joined.csv")
```
<br/>
## Creating objects in R
You can get output from R simply by typing math in the console:
```{r, purl = FALSE}
3 + 5
12 / 7
```
However, to do useful and interesting things, we need to assign _values_ to
_objects_. To create an object, we need to give it a name followed by the
assignment operator `<-`, and the value we want to give it:
```{r, purl = FALSE}
weight_kg <- 55
```
`<-` is the assignment operator. It assigns values on the right to objects on
the left. So, after executing `x <- 3`, the value of `x` is `3`. The arrow can
be read as 3 **goes into** `x`. For historical reasons, you can also use `=`
for assignments, but not in every context. Because of the
[slight](http://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html)
[differences](http://r.789695.n4.nabble.com/Is-there-any-difference-between-and-tp878594p878598.html)
in syntax, it is good practice to always use `<-` for assignments.
In RStudio, typing <kbd>Alt</kbd> + <kbd>-</kbd> (push <kbd>Alt</kbd> at the
same time as the <kbd>-</kbd> key) will write ` <- ` in a single keystroke in a PC, while typing <kbd>Option</kbd> + <kbd>-</kbd> (push <kbd>Option</kbd> at the
same time as the <kbd>-</kbd> key) does the same in a Mac.
Objects can be given any name such as `x`, `current_temperature`, or
`subject_id`. You want your object names to be explicit and not too long. They
cannot start with a number (`2x` is not valid, but `x2` is). R is case sensitive
(e.g., `weight_kg` is different from `Weight_kg`). There are some names that
cannot be used because they are the names of fundamental functions in R (e.g.,
`if`, `else`, `for`, see
[here](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html)
for a complete list). In general, even if it's allowed, it's best to not use
other function names (e.g., `c`, `T`, `mean`, `data`, `df`, `weights`). If in
doubt, check the help to see if the name is already in use. It's also best to
avoid dots (`.`) within an object name as in `my.dataset`. There are many
functions in R with dots in their names for historical reasons, but because dots
have a special meaning in R (for methods) and other programming languages, it's
best to avoid them. It is also recommended to use nouns for object names, and
verbs for function names. It's important to be consistent in the styling of your
code (where you put spaces, how you name objects, etc.). Using a consistent
coding style makes your code clearer to read for your future self and your
collaborators. In R, three popular style guides are
[Google's](https://google.github.io/styleguide/Rguide.xml), [Jean
Fan's](http://jef.works/R-style-guide/) and the
[tidyverse's](http://style.tidyverse.org/). The tidyverse's is very
comprehensive and may seem overwhelming at first. You can install the
[**`lintr`**](https://github.com/jimhester/lintr) package to automatically check
for issues in the styling of your code.
:::note
**Objects vs. variables**
What are known as `objects` in `R` are known as `variables` in many other
programming languages. Depending on the context, `object` and `variable` can
have drastically different meanings. However, in this lesson, the two words
are used synonymously. For more information see:
https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects
:::
When assigning a value to an object, R does not print anything. You can force R to print the value by using parentheses or by typing the object name:
```{r, purl = FALSE}
weight_kg <- 55 # doesn't print anything
(weight_kg <- 55) # but putting parenthesis around the call prints the value of `weight_kg`
weight_kg # and so does typing the name of the object
```
Now that R has `weight_kg` in memory, we can do arithmetic with it. For
instance, we may want to convert this weight into pounds (weight in pounds is 2.2 times the weight in kg):
```{r, purl = FALSE}
2.2 * weight_kg
```
We can also change an object's value by assigning it a new one:
```{r, purl = FALSE}
weight_kg <- 57.5
2.2 * weight_kg
```
This means that assigning a value to one object does not change the values of
other objects For example, let's store the animal's weight in pounds in a new
object, `weight_lb`:
```{r, purl = FALSE}
weight_lb <- 2.2 * weight_kg
```
and then change `weight_kg` to 100.
```{r, purl = FALSE}
weight_kg <- 100
```
What do you think is the current content of the object `weight_lb`? 126.5 or 220?
<br/>
### Comments in scripts
The comment character in R is `#`, anything to the right of a `#` in a script
will be ignored by R. It is useful to leave notes and explanations in your
scripts.
RStudio makes it easy to comment or uncomment a paragraph: after selecting the
lines you want to comment, press at the same time on your keyboard
<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>C</kbd>. If you only want to comment
out one line, you can put the cursor at any location of that line (i.e. no need
to select the whole line), then press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> +
<kbd>C</kbd>.
<br />
:::exercise
### Exercise - assigning values
What are the values after each statement in the following?
```{r, purl = FALSE}
mass <- 47.5 # mass?
age <- 122 # age?
mass <- mass * 2.0 # mass?
age <- age - 20 # age?
mass_index <- mass/age # mass_index?
```
<details><summary>Answer</summary>
```{purl = FALSE}
[1] 47.5 # mass
[1] 122 # age
[1] 95 # mass
[1] 102 # age
[1] 0.9313725 # mass_index
```
</details>
:::
<br/>
## Functions and their arguments
Functions are "canned scripts" that automate more complicated sets of commands
including operations assignments, etc. Many functions are predefined, or can be
made available by importing R *packages* (more on that later). A function
usually takes one or more inputs called *arguments*. Functions often (but not
always) return a *value*. A typical example would be the function `sqrt()`. The
input (the argument) must be a number, and the return value (in fact, the
output) is the square root of that number. Executing a function ('running it')
is called *calling* the function. An example of a function call is:
```{r, eval = FALSE, purl = FALSE}
b <- sqrt(a)
```
Here, the value of `a` is given to the `sqrt()` function, the `sqrt()` function
calculates the square root, and returns the value which is then assigned to
the object `b`. This function is very simple, because it takes just one argument.
The return 'value' of a function need not be numerical (like that of `sqrt()`),
and it also does not need to be a single item: it can be a set of things, or
even a dataset. We'll see that when we read data files into R.
Arguments can be anything, not only numbers or filenames, but also other
objects. Exactly what each argument means differs per function, and must be
looked up in the documentation (see below). Some functions take arguments which
may either be specified by the user, or, if left out, take on a *default* value:
these are called *options*. Options are typically used to alter the way the
function operates, such as whether it ignores 'bad values', or what symbol to
use in a plot. However, if you want something specific, you can specify a value
of your choice which will be used instead of the default.
Let's try a function that can take multiple arguments: `round()`.
```{r, results = 'show', purl = FALSE}
round(3.14159)
```
Here, we've called `round()` with just one argument, `3.14159`, and it has
returned the value `3`. That's because the default is to round to the nearest
whole number. If we want more digits we can see how to do that by getting
information about the `round` function. We can use `args(round)` to find what
arguments it takes, or look at the
help for this function using `?round`.
```{r, results = 'show', purl = FALSE}
args(round)
```
```{r, eval = FALSE, purl = FALSE}
?round
```
We see that if we want a different number of digits, we can
type `digits = 2` or however many we want.
```{r, results = 'show', purl = FALSE}
round(3.14159, digits = 2)
```
If you provide the arguments in the exact same order as they are defined you
don't have to name them:
```{r, results = 'show', purl = FALSE}
round(3.14159, 2)
```
And if you do name the arguments, you can switch their order:
```{r, results = 'show', purl = FALSE}
round(digits = 2, x = 3.14159)
```
It's good practice to put the non-optional arguments (like the number you're
rounding) first in your function call, and to then specify the names of all optional
arguments. If you don't, someone reading your code might have to look up the
definition of a function with unfamiliar arguments to understand what you're
doing.
<br/>
## Vectors and data types
A vector is the most common and basic data type in R, and is pretty much
the workhorse of R. A vector is composed by a series of values, which can be
either numbers or characters. We can assign a series of values to a vector using
the `c()` function. For example we can create a vector of animal weights and assign
it to a new object `weight_g`:
```{r, purl = FALSE}
weight_g <- c(50, 60, 65, 82)
weight_g
```
A vector can also contain characters:
```{r, purl = FALSE}
animals <- c("mouse", "rat", "dog")
animals
```
The quotes around "mouse", "rat", etc. are essential here. Without the quotes R
will assume objects have been created called `mouse`, `rat` and `dog`. As these objects
don't exist in R's memory, there will be an error message.
There are many functions that allow you to inspect the content of a
vector. `length()` tells you how many elements are in a particular vector:
```{r, purl = FALSE}
length(weight_g)
length(animals)
```
An important feature of a vector, is that all of the elements are the same type of data.
The function `class()` indicates the class (the type of element) of an object:
```{r, purl = FALSE}
class(weight_g)
class(animals)
```
An **atomic vector** is the simplest R **data type** and is a linear vector of a single type. Above, we saw
2 of the 6 main **atomic vector** types that R
uses: `"character"` and `"numeric"` (or `"double"`). These are the basic building blocks that
all R objects are built from. The other 4 **atomic vector** types are:
* `"logical"` for `TRUE` and `FALSE` (the boolean data type)
* `"integer"` for integer numbers (whole numbers)
* `"complex"` to represent complex numbers with real and imaginary parts (e.g.,
`1 + 4i`) and that's all we're going to say about them
* `"raw"` for bitstreams that we won't discuss further
You can check the type of your vector using the `typeof()` function and inputting your vector as the argument.
Vectors are one of the many **data structures** that R uses. Other important
ones are lists (`list`), matrices (`matrix`), data frames (`data.frame`),
factors (`factor`) and arrays (`array`).
<br/>
## Missing data
As R was designed to analyse datasets, it includes the concept of missing data
(which is uncommon in other programming languages). Missing data are represented
in vectors as `NA`.
When doing operations on numbers, most functions will return `NA` if the data
you are working with include missing values. This feature
makes it harder to overlook the cases where you are dealing with missing data.
You can add the argument `na.rm = TRUE` to calculate the result while ignoring
the missing values.
```{r, purl = FALSE}
heights <- c(2, 4, 4, NA, 6)
mean(heights)
max(heights)
mean(heights, na.rm = TRUE)
max(heights, na.rm = TRUE)
```
If your data include missing values, you may want to become familiar with the
functions `is.na()`, `na.omit()`, and `complete.cases()`. We will discuss dealing with missing values a bit later on.
Now that we have learned how to write scripts, and the basics of R's data
structures, we are ready to learn a bit more about using external functions in R.
## Packages
R has a lot of in-built functionality, such as the `sqrt`, `mean`, `max` functions that we have come across so far. This built-in functionality is what we refer to as **R Base**.
It is possible to extend this functionality by using external functions through **packages**. Packages in R are basically sets of additional functions that let you do more stuff.
### Tidyverse
The package that we will be using in this course is called **tidyverse.** It is an "umbrella-package" that contains several packages useful for data manipulation and visualisation which work well together such as **`readr`**, **`tidyr`**, **`dplyr`**, **`ggplot2`**, **`tibble`**, etc...
<center><img src="img/tidyverse_workflow.png" width = 75%/></center>
<br />
Tidyverse is a relatively recent package (launched in 2016) when compared to _R base_ (stable version in 2000), thus you will still come across R resources that do not use _tidyverse_. However, since its release, _tidyverse_ has been increasing in popularity throughout the R programming community and it is now very popular in Data Science as it was designed with the aim to help Data Scientists perform their tasks more efficiently.
Some of the main advantages of _tidyverse_ over _R base_ are:
1. **It is more verbose **
<p>Most tidyverse functions using common, meaningful words. For example, you can filter using `filter` or select data using `select`. </p>
2. **Faster**
<p>Using tidyverse is up to 10x faster[^1] when compared to the corresponding base R base functions.</p>
3. **It does not convert data upon importing**
<p>R Base has the somewhat annoying habit of converting data types when importing data, which can lead to problems when doing further analyses. With tidyverse, this does not happen.
[^1]: https://readr.tidyverse.org/
</p>
<br/>
### Installing and loading packages
Before using a package for the first time you will need to install it on your machine, and then you should import it in every subsequent R session when you need it. To install a package in R on your machine you need to use the `install.packages` function. To install the `tidyverse` package type the following straight into the console:
```{r, eval=FALSE, purl = FALSE}
# Install the tidyverse package
install.packages("tidyverse")
```
It is better to install packages straight from the console then from your script as there's no need to re-install packages every time you run the script.
Then, to load the package type:
```{r}
# Load the tidyverse package
library(tidyverse)
```
Now that we have loaded the `tidyverse` package in R we are now able to use its functions. We will now start working through the data exploration workflow by first importing data into R.
<br />