forked from LiamDBailey/introR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintro_R.qmd
779 lines (566 loc) · 12.8 KB
/
intro_R.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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
---
title: "Introduction to R"
author: Liam D. Bailey & Alexandre Courtiol
format:
revealjs:
toc: true
toc-depth: 1
theme: [moon, css/custom.scss]
highlight-style: a11y
self-contained: true
self-contained-math: true
editor_options:
chunk_output_type: console
---
# Installing R and R Studio
------------------------------
## What is R?
![](src/R_website.png)
## What is RStudio?
![](src/rstudio_website.png)
## What is RStudio?
![](src/rstudio_panes.png)
# R packages
------------------------------
## Installing and loading R packages {auto-animate="true"}
<br>
::: {.fragment}
```{r}
#| eval: false
#| echo: true
install.packages("tidyverse")
```
:::
<br>
::: {.fragment}
```{r}
#| echo: true
library(tidyverse)
```
:::
## Packages for this course
::: callout-note
INSTALL THESE ON YOUR SYSTEM NOW!
:::
```{r}
#| eval: false
#| echo: true
install.packages("adegenet")
install.packages("pegas")
install.packages("poppr")
install.packages("hierfstat")
install.packages("lattice")
```
## Updating R packages {auto-animate="true"}
```{r}
#| echo: true
packageVersion("ggplot2")
```
::: {.fragment}
![](src/update.png)
:::
# Good practice
## Good practice {auto-animate="true"}
### Set RStudio options
![](src/rstudio_options1.png)
## Good practice {auto-animate="true"}
### Set RStudio options
![](src/rstudio_options2.png)
## Good practice {auto-animate="true"}
### Save your script in a file
![](src/rstudio_panes.png)
**We'll talk about RMarkdown later**
## Good practice {auto-animate="true"}
### Use comments to understand your code better
```{r}
#| echo: true
#| eval: false
#| code-line-numbers: "1|2"
# EXPLAIN WHAT THE CODE DOES
my_code_here
```
# Basics of R: Functions
## Functions {auto-animate="true"}
<br>
(Generally) take an input and return an output in R. For example, the function `sum()` takes a numeric vector and will return a single value.
```{r}
#| echo: true
## Compute the sum of some numbers
sum(c(1, 3, 5, 1))
```
::: {.fragment}
::: callout-note
We'll discuss more what a **numeric vector** is soon.
:::
:::
## Functions {auto-animate="true"}
<br>
Trouble-shoot using `?` or `help()`
```{r}
#| echo: true
## Help documentation of the function sum()
help(sum)
?sum
```
You can learn what package the function is from, what the function does and what arguments it takes.
## Functions {auto-animate="true"}
![](src/help_doc.png)
## Functions {auto-animate="true"}
::: callout-warning
Different packages might have functions with the same name!
:::
`package::function()` is explicit about which package to use.
```{r}
#| echo: true
## In case of ambiguity, use :: and specify the package
base::sum(c(1, 3, 5, 1))
```
## Functions {auto-animate="true"}
<br>
If a function doesn't work it will display an error...
```{r}
#| echo: true
#| error: true
sum(-)
```
::: {.fragment}
...but these errors aren't always easy to read.
:::
# Basics of R: Object types
## Object types {auto-animate="true"}
<br>
Basic kinds of R objects (or 'classes')
```{r}
#| echo: true
## Character string
"word"
```
::: {.fragment}
```{r}
#| echo: true
## Numeric
1.2
```
:::
::: {.fragment}
```{r}
#| echo: true
## Logical (TRUE/FALSE)
TRUE
```
:::
::: {.fragment}
```{r}
#| echo: true
## Factor
factor(c("A", "B"), levels = c("A", "B"))
```
:::
## Object types {auto-animate="true"}
<br>
Use `str()` if you're unsure!
```{r}
#| echo: true
str("word")
```
::: {.fragment}
```{r}
#| echo: true
str(1.2)
```
:::
::: {.fragment}
```{r}
#| echo: true
str(TRUE)
```
:::
::: {.fragment}
```{r}
#| echo: true
str(factor(c("A", "B")))
```
:::
## Object types {auto-animate="true"}
<br>
Assign an object with `<-` or `->`
```{r}
#| echo: true
#| code-line-numbers: "1-2|4-5"
## Save value to use later!
my_object <- "A"
## Check what object we just created!
str(my_object)
```
# Vector
## Vector {auto-animate="true"}
<br>
$\geq$ 1 values of the **same type**
```{r}
#| echo: true
#| code-line-numbers: "1-2|4-5"
## Create a vector of numeric
my_vector <- c(1.2, 3.4, 0.1)
## Check the structure...
str(my_vector)
```
## Vector {auto-animate="true"}
<br>
$\geq$ 1 values of the [**same type**]{style="color:#ff2c2d;"}
```{r}
#| echo: true
#| code-line-numbers: "1-2|4-5"
## A vector *coerces* everything to be the same
my_vector <- c(115.3, -0.1, "2")
## Notice everything is character!
str(my_vector)
```
## Vector {auto-animate="true"}
<br>
Vectors have 1 dimension (a length)
```{r}
#| echo: true
## Find how many values are in your vector!
length(my_vector)
```
## Vector {auto-animate="true"}
<br>
Select particular values using 'indexing' with []
```{r}
#| echo: true
#| code-line-numbers: "1-2|4-5"
## 'Index' a vector using []
my_vector <- c("A", 115.3, -0.1)
## Find the first value in the vector
my_vector[1]
```
::: {.fragment}
```{r}
#| echo: true
## Find the first and third value in the vector
my_vector[c(1, 3)]
```
:::
::: {.fragment}
```{r}
#| echo: true
## Find everything *except* the second value in the vector
my_vector[-2]
```
:::
## Vector {auto-animate="true"}
<br>
Watch out for missing data.
```{r}
#| echo: true
#| code-line-numbers: "1-2|4|5|6|7|8"
# This numeric vector has some unusual values
missing_data <- c(NULL, 1.1, 0.2, NA, 7, NaN, Inf)
# NULL: Empty
# NA: Missing data (can be any type)
# NaN: Not a number (specific to numeric)
# Inf: Infinity
str(missing_data)
```
# Matrix
## Matrix {auto-animate="true"}
<br>
$\geq$ 1 values of the **same type** with **two dimensions**
```{r}
#| echo: true
## A vector only has one dimension (length)
c(1, 2, 3, 4)
```
::: {.fragment}
```{r}
#| echo: true
#| code-line-numbers: "1-4|6-7"
## A matrix has two dimensions (number rows and number columns)
## Create a 2x2 dimensional matrix
my_matrix <- matrix(c(1, 2, 3, 4),
nrow = 2, ncol = 2)
## Check the structure...
str(my_matrix)
```
:::
## Matrix {auto-animate="true"}
<br>
$\geq$ 1 values of the [**same type**]{style="color:#ff2c2d;"} with **two dimensions**
```{r}
#| echo: true
#| code-line-numbers: "1-4|6-7"
## A matrix will also coerce values!
my_matrix <- matrix(c("1", 2, 3, 4),
# Create a 2x2 matrix
nrow = 2, ncol = 2)
## Everything is character!
str(my_matrix)
```
## Matrix {auto-animate="true"}
<br>
$\geq$ 1 values of the **same type** with [**two dimensions**]{style="color:#ff2c2d;"}
```{r}
#| echo: true
## Find the number of rows in my matrix
nrow(my_matrix)
## Find the number of columns in my matrix
ncol(my_matrix)
```
## Matrix {auto-animate="true"}
Index a matrix with `[]`.
::: callout-warning
Remember, now we have two dimensions. So we index with [**ROW**]{style="color:#ff2c2d;"} then [**COLUMN**]{style="color:#ff2c2d;"}.
:::
```{r}
#| echo: true
## Find the value at row 1 and column 2
my_matrix[1, 2]
```
::: {.fragment}
```{r}
#| echo: true
## Find all values in row 1
my_matrix[1, ]
```
:::
::: {.fragment}
```{r}
#| echo: true
## Find all values in column 2
my_matrix[, 2]
```
:::
# List
## List {auto-animate="true"}
Contains any number of items.
Each item can be a [**different type**]{style="color:#ff2c2d;"}.
```{r}
#| echo: true
## Storing in a vector or matrix coerces everything to be the same
c(c(1, 2, 3), c("A", "B", "C"), c(3, 4, 5))
```
::: {.fragment}
```{r}
#| echo: true
## Use lists to store character and numeric data in one object
my_list <- list(c(1, 2, 3),
c("A", "B", "C"),
c(3, 4, 5))
my_list
```
:::
## List {auto-animate="true"}
Contains any number of items.
Each item can be a [**different type**]{style="color:#ff2c2d;"}.
```{r}
#| echo: true
## Check the structure
str(my_list)
```
## List {auto-animate="true"}
<br>
A list has [**one dimension**]{style="color:#ff2c2d;"} (length: the number of items in the list)
```{r}
#| echo: true
## Number of items in the list
length(my_list)
```
## List {auto-animate="true"}
We can index a list with `[]` and `[[]]`.
::: callout-warning
They have slightly different meanings!
:::
```{r}
#| echo: true
## Use `[]` to create a smaller list
## Create a new list with item 1 and 3
my_list[c(1, 3)]
```
::: {.fragment}
```{r}
#| echo: true
## Use `[[]]` to access the items inside the list
## Return list item 1
my_list[[1]]
```
:::
## List {auto-animate="true"}
When list-elements are named, they can be accessed using either `[[]]` or `$`.
```{r}
#| echo: true
## Create a named list
my_named_list <- list(first = c(1, 2, 3),
second = c("A", "B", "C"),
third = c(3, 4, 5))
str(my_named_list)
## Use `[[]]` to access the items inside the list
my_named_list[["first"]] # same as my_named_list[[1]]
## Use `$` to access the items inside the list
my_named_list$first
```
## List {auto-animate="true"}
::: callout-note
Many advanced functions will store their output as a list object.
Remember, you can use `str()` to understand them better.
:::
```{r}
#| echo: true
# These objects have a nice print output
model <- lm(Sepal.Length ~ Sepal.Width, data = iris)
model
```
## List {auto-animate="true"}
::: callout-note
Many advanced functions will store their output as a list object.
Remember, you can use `str()` to understand them better.
:::
```{r}
#| echo: true
# Internally, they have a lot more information!
str(model)
```
# Data frame
## Data frame {auto-animate="true"}
A special type of list:
- Each item in the list (i.e. column) is a vector ([**same type**]{style="color:#ff2c2d;"})
- All items in the list are the [**same length**]{style="color:#ff2c2d;"}
- Each item has a [**unique name**]{style="color:#ff2c2d;"}
```{r}
#| echo: true
## Create our own data frame!
my_df <- data.frame(col1 = c(1, 2, 3, 4),
col2 = c("A", "B", "C", "D"),
col3 = c(3, 4, 5, 6))
my_df
```
## Data frame {auto-animate="true"}
A special type of list:
- Each item in the list (i.e. column) is a vector ([**same type**]{style="color:#ff2c2d;"})
- All items in the list are the [**same length**]{style="color:#ff2c2d;"}
- Each item has a [**unique name**]{style="color:#ff2c2d;"}
```{r}
#| echo: true
## Check the structure
str(my_df)
```
## Data frame {auto-animate="true"}
<br>
A data frame has [**two dimensions**]{style="color:#ff2c2d;"} (number of rows and number of columns).
```{r}
#| echo: true
## Number of rows...
nrow(my_df)
## Number of columns...
ncol(my_df)
```
## Data frame {auto-animate="true"}
<br>
We can index using `[]` (just like a matrix) or using column names
```{r}
#| echo: true
## Items in rows 1 and 2 from column 2
my_df[c(1, 2), 2]
```
::: {.fragment}
```{r}
#| echo: true
## All items in column 2
my_df[, 2]
```
:::
::: {.fragment}
```{r}
#| echo: true
## All items in column named 'col2'
my_df$col2
```
:::
## Data frame {auto-animate="true"}
<br>
Usually we create a data frame by reading in a .csv file!
```{r}
#| echo: true
#| code-line-numbers: "1-2|4-5"
## Items in rows 1 and 2 from column 2
iris_df <- read.csv("iris.csv")
str(iris_df)
```
## Data frame {auto-animate="true"}
Use functions `head()`, `tail()`, or `summary()` to investigate a large data frame.
```{r}
#| echo: true
## A summary of all the columns
summary(iris_df)
```
## Data frame {auto-animate="true"}
Use functions `head()`, `tail()`, or `summary()` to investigate a large data frame.
```{r}
#| echo: true
## The first few rows of data...
head(iris_df)
```
# Using RMarkdown
## Using RMarkdown {auto-animate="true"}
RMarkdown (.Rmd) file is a great way to record and share your analyses!
![](src/Rmd_example.png)
## Using RMarkdown {auto-animate="true"}
Include code and output in the same document.
```{r}
#| echo: fenced
## Write your code inside these 'chunks'
c(1, 2, 3, 4)
```
## Using RMarkdown {auto-animate="true"}
Include plots to make a report.
```{r}
#| echo: fenced
plot(Sepal.Length ~ Sepal.Width, data = iris_df)
```
## Using RMarkdown {auto-animate="true"}
Write plain text to keep notes
````
# Section header
## Section subheader
Some notes about my code **in bold**. Below I include my code chunk...
```{{r}}
1 + 1
```
Some more notes...
````
## Using RMarkdown {auto-animate="true"}
'knit' your notes to create a report
::: columns
::: {.column width="50%"}
````
# Section header
## Section subheader
Some notes about my code **in bold**. Below I include my code chunk...
```{{r}}
1 + 1
```
Some more notes...
````
:::
::: {.column width="50%"}
![](src/knit_example.png)
:::
:::
## Using RMarkdown {auto-animate="true"}
'knit' your notes to create a report
![](src/knit_button.png)
## Using RMarkdown {auto-animate="true"}
::: callout-note
TEST YOUR KNOWLEDGE
:::
## Using RMarkdown {auto-animate="true"}
- Create a new RMarkdown file in RStudio (File > New File > RMarkdown)
- Create a new chunk of R code:
```{r}
#| echo: true
#| eval: false
mean(c(1, 2, "3", 4, NA))
```
- Knit the document to html.
- Check the document. Does the code work properly? Can you use you work out why?
- **BONUS**: Search for the RMarkdown Cheatsheet online and try adding some headers and bold text.
- **BONUS**: Knit the document to PDF.