-
Notifications
You must be signed in to change notification settings - Fork 11
/
r-tidyverse.qmd
1763 lines (1292 loc) · 55.1 KB
/
r-tidyverse.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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: Introduction to R and the Tidyverse
author: Clemens Schmid
format:
html:
link-external-icon: true
link-external-newwindow: true
editor_options:
chunk_output_type: console
bibliography: assets/references/r-tidyverse.bib
---
::: callout-note
This session is typically ran in parallel to the Introduction to Python and Pandas.
Participants of the summer schools choose which to attend based on their prior experience.
We recommend this session if you have no experience with neither R nor Python.
:::
::: {.callout-note collapse="true" title="Self guided: chapter environment setup"}
For this chapter's exercises, if not already performed, you will need to download the chapter's dataset, decompress the archive, and create and activate the conda environment.
To do this, use `wget` or right click and save to download this Zenodo archive: [10.5281/zenodo.13758879](https://doi.org/10.5281/zenodo.13758879), and unpack
```bash
tar xvf r-tidyverse.tar.gz
cd r-tidyverse/
```
You can then create and subsequently activate the conda environment with
```bash
conda env create -f r-tidyverse.yml
conda activate r-tidyverse
```
::: {.callout-tip title="README if you already have Rstudio installed and don't need conda" collapse=true}
Open Rstudio, and check that you have the two following packages installed.
```{r, eval=FALSE}
library(tidyverse)
library(palmerpenguins)
```
If one or neither are installed, please install as follows.
Delete already-installed packages from the function as necessary.
```{r, eval=FALSE}
install.packages(c("tidyverse", "palmerpenguins"))
```
:::
::: {.callout-tip title="README if you want to create the test datasets yourself from the palmerpenguins package" collapse=true}
```{r, eval=FALSE}
install.packages(c("tidyverse", "palmerpenguins"))
library(magrittr)
set.seed(5678)
peng_prepped <- palmerpenguins::penguins %>%
dplyr::filter(
!dplyr::if_any(
.cols = tidyselect::everything(),
.fns = is.na
)
) %>%
tibble::add_column(., id = 1:nrow(.), .before = "species")
peng_prepped %>%
dplyr::slice_sample(n = 300) %>%
dplyr::arrange(id) %>%
dplyr::select(-bill_length_mm, -bill_depth_mm) %>%
readr::write_csv("penguins.csv")
peng_prepped %>%
dplyr::slice_sample(n = 300) %>%
dplyr::arrange(id) %>%
dplyr::select(id, bill_length_mm, bill_depth_mm) %>%
readr::write_csv("penguin_bills.csv")
```
:::
:::
```{r, echo=FALSE, eval=FALSE}
# This code chunk is invisible and does not get evaluated. It contains notes on
# how to best present/introduce/present this chapter in the context of the SPAAM
# summer school. We assume a 2*2h time window for the r-tidyverse course:
## Share some audience survey questions and discuss the results ##
# 1. Do you agree with the following statement?
# "It is generally better to perform scientific data analysis in a scripting language
# like R or Python than in a spreadsheet application like LibreOffice Calc or
# Microsoft Excel?"
# Answer options: Yes | Rather yes | Rather no | No
# 2. Do you agree with the following statement? "Open source software is generally
# better for scientific data analysis than proprietary, closed source software."
# Answer options: Yes | Rather yes | Rather no | No
# 3. How would you rate your overall skill-level with R?
# Answer options: A number between 1 and 10
## Prepare the working environment in the virtual machine ##
# 1. Activate conda environment
# conda activate r-tidyverse
# 2. Start rstudio
# rstudio (in the the same console)
# 3. Create new RStudio project
# File -> New Project... -> Existing directory -> Select
# /vol/volume/r-tidyverse
# -> Create Project
# 4. Create script file
# File -> New File -> New Rscript
# Save file (Ctrl+S) and assign a name "sript.R"
## Give a brief tour of RStudio and its different panels ##
## Show some R finger exercises ##
# Start in console and then immediately move up to a script file
# Explain how to use Crtl+Enter to send code to the console
# R as a calculator
1 + 1
-5 + 10
3^2
# basic mathematical functions
sqrt(9)
exp(10)
log(22000)
# writing values into variables
a <- 8
b <- 1
1 + a
b + a
my_sum <- a + b
sqrt(my_sum)
# vectors - list of values
c(1,2,3)
v <- c(1,2,3)
mean(v)
sum(v)
# vectorized computation
c(1,2,3) + 5
v * 5
v + v
# functions with multiple arguments
v1 <- c(1,2,3)
v2 <- c(1,2.5,3)
plot(v1,v2)
cor(v1,v2)
cor(x = v1, y = v2)
cor(x = v1, y = v2, method = "pearson")
cor(x = v1, y = v2, method = "kendall")
# beyond numbers: strings
"Clemens Schmid"
s <- "Clemens Schmid"
tolower(s)
toupper(s)
paste(s,s)
grepl("Clemenx", s)
# vectors of strings
ss <- c("a", "b", "c")
toupper(ss)
paste(ss, collapse = ", ")
# searching an filtering in vectors
ss == "a"
v == 2
v > 1
v >= 2
# subsetting vectors
v
v[1]
v[1:3]
v[c(TRUE, FALSE, TRUE)]
v[v >= 2]
# data.frames: multiple vectors form a table
data.frame(
x = c(1,2,3),
y = c("a", "b", "c")
)
tibble::tibble(
x = c(1,2,3),
y = c("a", "b", "c")
)
## Let the participants work on the book chapter ##
# https://www.spaam-community.org/intro-to-ancient-metagenomics-book/r-tidyverse.html
# Share warning with the participants:
# > Don't burn through the chapter too quickly!
# > 1. Read the help files and look at the examples at the bottom of the help files
# > 2. Experiment with each function, so try things beyond the provided examples
# > 3. Cycle back and plot data after you modified it or created new data products
# Ask the participants to frequently report their progress on a survey system,
# so that you always know where they stand. Monitor this system.
# Be available for questions and visit the participants to see how they are progressing
## Discuss solutions for the exercises when most participants completed them ##
library(ggplot2)
library(magrittr)
## 8.4.7 ##
# Look at the mtcars dataset and read up on the meaning of its variables with the help operator ?. mtcars is a test dataset integrated in R and can always be accessed just by typing mtcars in the console.
?mtcars
# [, 1] mpg Miles/(US) gallon
# [, 2] cyl Number of cylinders
# [, 3] disp Displacement (cu.in.)
# [, 4] hp Gross horsepower
# [, 5] drat Rear axle ratio
# [, 6] wt Weight (1000 lbs)
# [, 7] qsec 1/4 mile time
# [, 8] vs Engine (0 = V-shaped, 1 = straight)
# [, 9] am Transmission (0 = automatic, 1 = manual)
# [,10] gear Number of forward gears
# [,11] carb Number of carburetors
# Visualise the relationship between Gross horsepower and 1/4 mile time.
ggplot(mtcars) +
geom_point(aes(x = hp, y = qsec))
# Integrate the Number of cylinders into your plot as an additional variable.
ggplot(mtcars) +
geom_point(aes(x = hp, y = qsec, color = as.character(cyl)))
# Additional insights: Combining multiple geoms
ggplot(
data = mtcars,
mapping = aes(x = hp, y = qsec)
) +
geom_point()
ggplot(
data = mtcars,
mapping = aes(x = hp, y = qsec)
) +
geom_point() +
geom_smooth(method = "lm") +
geom_text(aes(label = cyl))
merc <- mtcars %>%
tibble::as_tibble(rownames = "car_name") %>%
dplyr::filter(grepl("Merc", car_name))
ggplot(
data = mtcars,
mapping = aes(x = hp, y = qsec)
) +
geom_point() +
geom_smooth(method = "lm") +
geom_text(
data = merc,
mapping = aes(x = hp, y = qsec, label = car_name)
)
ggplot(
data = mtcars,
mapping = aes(x = hp, y = qsec)
) +
geom_point() +
geom_smooth(method = "lm") +
ggrepel::geom_text_repel(
data = merc,
mapping = aes(x = hp, y = qsec, label = car_name),
box.padding = 0.8
)
# Additional insights: Saving a ggplot
p <- ggplot(
data = mtcars,
mapping = aes(x = hp, y = qsec)
) +
geom_point() +
geom_smooth(method = "lm") +
ggrepel::geom_text_repel(
data = merc,
mapping = aes(x = hp, y = qsec, label = car_name),
box.padding = 0.8
)
ggsave(
"mtcars_qsec_hp.pdf",
plot = p,
device = "pdf",
scale = 0.5,
dpi = 300,
width = 300, height = 250, units = "mm"
)
## 8.5.6 ##
# Determine the number of cars with four forward gears (gear) in the mtcars dataset.
mtcars %>%
dplyr::filter(gear == 4) %>%
nrow()
# Determine the mean 1/4 mile time (qsec) per Number of cylinders (cyl) group.
mean_qsec_per_cyl <- mtcars %>%
dplyr::group_by(cyl) %>%
dplyr::summarise(
qsec_mean = mean(qsec)
)
# Additional insights: Use derived data products in plots
ggplot(
data = mtcars,
mapping = aes(x = as.factor(cyl), y = qsec)
) +
geom_boxplot() +
geom_point() +
geom_point(
data = mean_qsec_per_cyl,
mapping = aes(x = as.factor(cyl), y = qsec_mean),
color = "red"
)
# Identify the least efficient cars for both transmission types (am).
# make the care name an explicit column
mtcars2 <- tibble::rownames_to_column(mtcars, var = "car")
# Solution 1
mtcars2 %>%
dplyr::group_by(am) %>%
dplyr::arrange(mpg) %>%
dplyr::slice_head(n = 1) %$%
car
# Solution 1 only returns n = 1 result per group even if
# there are multiple cars with the same minimal mpg value.
# Solution 2 shows both, if this is desired.
# Solution 2
mtcars2 %>%
dplyr::group_by(am) %>%
dplyr::filter(mpg == min(mpg)) %$%
car
## 8.6.5 ##
# Move the column gear to the first position of the mtcars dataset.
mtcars %>%
dplyr::relocate(gear, .before = mpg) %>%
tibble::as_tibble() # transforming the raw dataset for better printing
# Make a new dataset mtcars2 from mtcars with only the columns gear and am_v. am_v should be a new column which encodes the _transmission type_ (am) as either "manual" or "automatic".
mtcars2 <- mtcars %>%
dplyr::transmute(
gear,
am_v = dplyr::case_match(
am,
0 ~ "automatic",
1 ~ "manual"
)
) %>%
tibble::as_tibble()
mtcars2
# Count the number of cars per transmission type (am_v) and number of gears (gear) in mtcars2. Then transform the result to a wide format, with one column per transmission type.
mtcars2 %>%
dplyr::group_by(am_v, gear) %>%
dplyr::tally() %>%
tidyr::pivot_wider(
names_from = am_v,
values_from = n
)
## End the course ##
# Re-run the crucial starting question:
# How would you rate your overall skill-level with R?
# Answer options: A number between 1 and 10
# Discuss any open questions/comments
```
```{r, echo=FALSE}
# Set global options
knitr::opts_chunk$set(attr.output = "style='border: 1px; border-style: solid; margin-left: 10px; margin-right: 10px;'")
```
## R, RStudio, the tidyverse and penguins
This chapter introduces the statistical programming environment R and how to use it with the RStudio editor.
It is structured as self-study material with examples and little exercises to be completed in one to four hours.
A larger exercise at the end pulls the individual units together.
The didactic idea behind this tutorial is to get as fast as possible to tangible, useful output, namely data visualisation.
So we will first learn about reading and plotting data, and only later go to some common operations like conditional queries, data structure transformation and joins.
We will focus exclusively on tabular data and how to handle it with the packages in the tidyverse framework.
The example data used here is an ecological dataset about penguins.
So here is what you need to know for the beginning:
- R [@RCoreTeam2023] is a fully featured programming language, but it excels as an environment for (statistical) data analysis (<https://www.r-project.org>)
- RStudio [@RstudioTeam] is an integrated development environment (IDE) for R (and other languages) (<https://www.rstudio.com/products/rstudio>)
- The tidyverse [@Wickham2019-ot] is a powerful collection of R packages with well-designed and consistent interfaces for the main steps of data analysis: loading, transforming and plotting data (<https://www.tidyverse.org>). This tutorial works with tidyverse ~v2.0. We will learn about the packages `readr`, `tibble`, `ggplot2`, `dplyr`, `magrittr` and `tidyr`. `forcats` will be briefly mentioned, but `purrr` and `stringr` are left out.
- The `palmerpenguins` package [@Horst2020] provides a neat example dataset to learn data exploration and visualisation in R (<https://allisonhorst.github.io/palmerpenguins>)
## Loading R Studio and preparing a project
Before we begin, we can load RStudio from within your `conda` environment, by running the following.
```bash
rstudio
```
:::{.callout-caution}
It is _not_ recommended to download and update Rstudio if asked to on loading while following this textbook or during the summer school.
You do so at your own risk.
We recommend pressing 'Remind later' or 'Ignore'.
:::
The RStudio window should then open.
Open RStudio and create a new project by going to the top tool bar, and selecting `File` -> `New Project...`.
When asked, create the new directory in an 'Existing directory' and select the `r-tidyverse/` directory.
Once created, add new R script file so that you can copy the relevant code from this textbook into it to run them by pressing in the top tool bar `File` -> `New File` -> `New Rscript`.
## Loading data into tibbles
### Reading tabular data with readr
With R we usually operate on data in our computer's memory.
The tidyverse provides the package `readr` to read data from text files into memory, both from our file system or the internet.
It provides functions to read data in almost any (text) format.
```{r eval=FALSE}
readr::read_csv() # .csv files (comma-separated) -> see penguins.csv
readr::read_tsv() # .tsv files (tab-separated)
readr::read_delim() # tabular files with arbitrary separator
readr::read_fwf() # fixed width files (each column with a set number of tokens)
readr::read_lines() # files with any content per line for self-parsing
```
### How does the interface of `read_csv` work?
We can learn more about any R function with the `?` operator: To open a help file for a specific function run `?<function_name>` (e.g. `?readr::read_csv`) in the R console.
`readr::read_csv` has many options to specify how to read a text file.
```{r eval=FALSE}
read_csv(
file, # The path to the file we want to read
col_names = TRUE, # Are there column names?
col_types = NULL, # Which types do the columns have? NULL -> auto
locale = default_locale(), # How is information encoded in this file?
na = c("", "NA"), # Which values mean "no data"
trim_ws = TRUE, # Should superfluous white-spaces be removed?
skip = 0, # Skip X lines at the beginning of the file
n_max = Inf, # Only read X lines
skip_empty_rows = TRUE, # Should empty lines be ignored?
comment = "", # Should comment lines be ignored?
name_repair = "unique", # How should "broken" column names be fixed
...
)
```
When calling this - or any - function in R, we can either set the arguments explicitly by name or just by listing them in the correct order. That means `readr::read_csv(file = "path/to/file.csv")` and `readr::read_csv("path/to/file.csv")` are identical, because `file = ...` is the first argument of `readr::read_csv()`.
### What does `readr` produce? The `tibble`!
To read a .csv file (here `"penguins.csv"`) into a variable (here `peng_auto`) run the following.
```{r, eval=FALSE}
peng_auto <- readr::read_csv("penguins.csv")
```
```{r, echo=FALSE}
# this version is only for the website!
peng_auto <- readr::read_csv("assets/data/r-tidyverse/penguins.csv")
```
As a by-product of reading the file `readr` also prints some information on the number and type of rows and columns it discovered in the file.
It automatically detects column types - but you can also define them manually.
```{r, eval=FALSE}
peng <- readr::read_csv(
"penguins.csv",
col_types = "iccddcc" # this string encodes the desired types for each column
)
```
The `col_types` argument takes a string with a list of characters, where each character denotes one columns types.
Possible types are `c` = character, `i` = integer, `d` = double, `l` = logical, etc. Remember that you can check `?readr::read_csv` for more.
```{r, echo=FALSE}
# this version is only for the website!
peng <- readr::read_csv(
"assets/data/r-tidyverse/penguins.csv",
col_types = "iccddcc" # this string encodes the desired types for each column
)
```
`readr` finally returns an in-memory representation of the data in the file, a `tibble`.
A `tibble` is a "data frame", a tabular data structure with rows and columns. Unlike a simple array, each column can have another data type.
### How to look at a `tibble`?
Typing the name of any object into the R console will print an overview of it to the console.
```{r}
peng
```
But there are various other ways to inspect the content of a `tibble`
```{r, eval=FALSE}
str(peng) # A structural overview of an R object
summary(peng) # A human-readable summary of an R object
View(peng) # Open RStudio's interactive data browser
```
## Plotting data in `tibble`s
### `ggplot2` and the "grammar of graphics"
To understand and present data, we usually have to visualise it.
`ggplot2` is an R package that offers a slightly unusual, but powerful and logical interface for this task [@Wickham2016].
The following example describes a stacked bar chart.
```{r}
library(ggplot2) # Loading a library to use its functions without ::
```
```{r}
ggplot( # Every plot starts with a call to the ggplot() function
data = peng # This function can also take the input tibble in the data argument
) + # The plot consists of individual functions linked with "+"
geom_bar( # "geoms" define the plot layers we want to draw,
# so in this case a bar-chart
mapping = aes( # The aes() function maps variables to visual properties
x = island, # publication_year -> x-axis
fill = species # community_type -> fill colour
)
)
```
A `geom_*` combines data (here `peng`), a geometry (here vertical, stacked bars) and a statistical transformation (here counting the number of penguins per island and species). Each `geom` has different visual elements (e.g. an x- and a y-axis, shape and size of geometric elements, fill and border colour, ...) to which we can *map* certain variables (columns) of our input dataset. The visual elements will then represent these variables in the plot. `ggplot2` features many `geoms`: A good overview is provided by this cheatsheet: [https://rstudio.github.io/cheatsheets/html/data-visualization.html](https://rstudio.github.io/cheatsheets/html/data-visualization.html).
Beyond `geom`s, a ggplot2 plot can be further specified with (among others) `scale`s, `facet`s and `theme`s.
### `scale`s control the exact behaviour of visual elements
Here is another plot to demonstrate this: Boxplots of penguin weight per species.
```{r}
ggplot(peng) +
geom_boxplot(mapping = aes(x = species, y = body_mass_g))
```
Let's assume we had some extreme outliers in this dataset. To simulate this, we replace some random weights with extreme values.
```{r}
set.seed(1234) # we set a seed for reproducible randomness
peng_out <- peng
peng_out$body_mass_g[sample(1:nrow(peng_out), 10)] <- 50000 + 50000 * runif(10)
```
Now we plot the dataset with these "outliers".
```{r}
ggplot(peng_out) +
geom_boxplot(aes(x = species, y = body_mass_g))
```
This is not well readable, because the extreme outliers dictate the scale of the y-axis.
A 50+kg penguin is a scary thought and we would probably remove these outliers, but let's assume they were valid observation we want to include in the plot.
To mitigate the visualisation issue we can change the **scale** of different visual elements - e.g. the y-axis.
```{r}
ggplot(peng_out) +
geom_boxplot(aes(x = species, y = body_mass_g)) +
scale_y_log10() # adding the log-scale improves readability
```
We will now go back to the normal dataset without the artificial outliers.
### Colour `scale`s
(Fill) colour is a visual element of a plot and its scaling can be adjusted as well.
```{r}
ggplot(peng) +
geom_boxplot(aes(x = species, y = body_mass_g, fill = species)) +
scale_fill_viridis_d(option = "C")
```
We use the `scale_*` function to select one of the visually appealing (and robust to colourblindness) viridis colour palettes ([https://cran.r-project.org/web/packages/viridis/vignettes/intro-to-viridis.html](https://cran.r-project.org/web/packages/viridis/vignettes/intro-to-viridis.html)).
### More variables! Defining plot matrices via `facet`s
In the previous example we didn't add additional information with the fill colour, as the plot already distinguished by species on the x-axis.
We can instead use colour to encode more information, for example by mapping the variable sex to it.
```{r}
ggplot(peng) +
geom_boxplot(aes(x = species, y = body_mass_g, fill = sex))
```
Note how mapping another variable to the fill colour automatically splits the dataset and how this is reflected in the number of boxplots per species.
Another way to visualise more variables in one plot is to split the plot by categories into **facets**, so sub-plots per category.
Here we split by sex, which is already mapped to the fill colour:
```{r}
ggplot(peng) +
geom_boxplot(aes(x = species, y = body_mass_g, fill = sex)) +
facet_wrap(~sex)
```
The fill colour is therefore free again to show yet another variable, for example the year a given penguin was examined.
```{r}
ggplot(peng) +
geom_boxplot(aes(x = species, y = body_mass_g, fill = year)) +
facet_wrap(~sex)
```
This plot already visualises the relationship of four variables: species, body mass, sex and year of observation.
### Setting purely aesthetic settings with `theme`
Aesthetic changes can be applied as part of the `theme`, which allows for very detailed configuration (see `?theme`).
Here we rotate the x-axis labels by 45°, which often helps to resolve over-plotting.
```{r}
ggplot(peng) +
geom_boxplot(aes(x = species, y = body_mass_g, fill = year)) +
facet_wrap(~sex) +
theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))
```
### Ordering elements in a plot with `factors`
R supports defining ordinal data with `factor`s.
This can be used to set the order of elements in a plot, e.g. the order of bars in a bar chart.
We do not cover `factor`s beyond the following example here, although the tidyverse includes a package (`forcats`) specifically for handling them.
Elements based on `character` columns are by default ordered alphabetically.
```{r}
ggplot(peng) +
geom_bar(aes(x = species)) # bars are alphabetically ordered
```
With `forcats::fct_reorder` we can transform an input vector to a `factor`, ordered by a summary statistic (even based on another vector).
```{r}
peng2 <- peng
peng2$species_ordered <- forcats::fct_reorder(
peng2$species,
peng2$species, length
)
```
With this change, the plot will be ordered according to the intrinsic order defined for `species_ordered`.
```{r}
ggplot(peng2) +
geom_bar(aes(x = species_ordered)) # bars are ordered by size
```
### Exercise
1. Look at the `mtcars` dataset and read up on the meaning of its variables with the help operator `?`.
`mtcars` is a test dataset integrated in R and can always be accessed just by typing `mtcars` in the console.
2. Visualise the relationship between _Gross horsepower_ and _1/4 mile time_.
```{r}
```
3. Integrate the _Number of cylinders_ into your plot as an additional variable.
```{r}
```
::: {.callout-tip title="Possible solutions" collapse=true}
```{r, eval=FALSE}
?mtcars
```
```
[, 1] mpg Miles/(US) gallon
[, 2] cyl Number of cylinders
[, 3] disp Displacement (cu.in.)
[, 4] hp Gross horsepower
[, 5] drat Rear axle ratio
[, 6] wt Weight (1000 lbs)
[, 7] qsec 1/4 mile time
[, 8] vs Engine (0 = V-shaped, 1 = straight)
[, 9] am Transmission (0 = automatic, 1 = manual)
[,10] gear Number of forward gears
[,11] carb Number of carburetors
```
```{r}
ggplot(mtcars) +
geom_point(aes(x = hp, y = qsec))
```
```{r}
ggplot(mtcars) +
geom_point(aes(x = hp, y = qsec, color = as.factor(cyl)))
```
:::
## Conditional queries on tibbles
### Selecting columns and filtering rows with `select` and `filter`
```{r, echo=FALSE}
# technical adjustments for rendering
old_options <- options(
pillar.print_max = 5,
pillar.print_min = 5,
pillar.advice = FALSE
)
```
Among the most basic tabular data transformation operations is the conditional selection of columns and rows.
The `dplyr` package includes powerful functions to subset data in tibbles.
`dplyr::select` allows to select columns:
```{r}
dplyr::select(peng, id, flipper_length_mm) # select two columns
dplyr::select(peng, -island, -flipper_length_mm) # remove two columns
```
`dplyr::filter` allows for conditional filtering of rows:
```{r}
dplyr::filter(peng, year == 2007) # penguins examined in 2007
# penguins examined in 2007 OR 2009
dplyr::filter(peng, year == 2007 | year == 2009)
# an alternative way to express OR with the match operator "%in%"
dplyr::filter(peng, year %in% c(2007, 2009))
# Adelie penguins heavier than 4kg
dplyr::filter(peng, species == "Adelie" & body_mass_g >= 4000)
```
Note how each function here takes `peng` as a first argument. This invites a more elegant syntax.
### Chaining functions together with the pipe `%>%`
A core feature of the tidyverse is the pipe `%>%` in the `magrittr` package.
This 'infix' operator allows to chain data and operations for concise and clear data analysis syntax.
```{r}
library(magrittr)
peng %>% dplyr::filter(year == 2007)
```
It forwards the LHS (left-hand side) of `%>%` as the first argument of the function appearing on the RHS (right-hand side) to enable sequences of function calls ("tidyverse style").
```{r}
peng %>%
dplyr::select(id, species, body_mass_g) %>%
dplyr::filter(species == "Adelie" & body_mass_g >= 4000) %>%
nrow() # count the resulting rows
```
`magrittr` also offers some more operators, among which the extraction operator `%$%` is particularly useful to easily extract individual variables from a tibble.
```{r}
peng %>%
dplyr::filter(island == "Biscoe") %$%
species %>% # extract the species column as a vector
unique() # get the unique elements of said vector
```
Here we already use the base R summary function `unique`.
### Summary statistics in `base` R
Summarising and counting data is indispensable and R offers a variety of basic operations in its `base` package.
Many of them operate on `vector`s, so lists of values of one type.
Individual columns are vectors.
```{r}
# we extract a single variable as a vector of values
chinstraps_weights <- peng %>%
dplyr::filter(species == "Chinstrap") %$%
body_mass_g
chinstraps_weights
length(chinstraps_weights) # length/size of a vector
unique(chinstraps_weights) # unique elements of a vector
min(chinstraps_weights) # minimum
max(chinstraps_weights) # maximum
mean(chinstraps_weights) # mean
median(chinstraps_weights) # median
var(chinstraps_weights) # variance
sd(chinstraps_weights) # standard deviation
# quantiles for the given probabilities
quantile(chinstraps_weights, probs = c(0.25, 0.75))
```
Many of these functions can ignore missing values (so `NA` values) with the option `na.rm = TRUE`.
### Group-wise summaries with `group_by` and `summarise`
These vector summary statistics are particular useful when applied to conditional subsets of a dataset.
`dplyr` allows such summary operations with a combination of the functions `group_by` and `summarise`, where the former tags a `tibble` with categories based on its variables and the latter reduces it to these groups while simultaneously creating new columns.
```{r}
peng %>%
# group the tibble by the material column
dplyr::group_by(species) %>%
dplyr::summarise(
# new col: min weight for each group
min_weight = min(body_mass_g),
# new col: median weight for each group
median_weight = median(body_mass_g),
# new col: max weight for each group
max_weight = max(body_mass_g)
)
```
Grouping can also be applied across multiple columns at once.
```{r}
peng %>%
# group by species and year
dplyr::group_by(species, year) %>%
dplyr::summarise(
# new col: number of penguins for each group
n = dplyr::n(),
# drop the grouping after this summary operation
.groups = "drop"
)
```
If we group by more than one variable, then `summarise` will not entirely remove the group tagging when generating the result dataset.
We can force this with `.groups = "drop"` to avoid undesired behaviour with this dataset later on.
### Sorting and slicing tibbles with `arrange` and `slice`
`dplyr` allows to `arrange` tibbles by one or multiple columns.
```{r}
peng %>% dplyr::arrange(sex) # sort by sex
peng %>% dplyr::arrange(sex, body_mass_g) # sort by sex and weight
peng %>% dplyr::arrange(dplyr::desc(body_mass_g)) # sort descending
```
Sorting also works within groups and can be paired with `slice` to extract extreme values per group.
Here we extract the three heaviest individuals per species.
```{r}
peng %>%
dplyr::group_by(species) %>% # group by species
dplyr::arrange(dplyr::desc(body_mass_g)) %>% # sort by weight within groups
dplyr::slice_head(n = 3) %>% # keep the first three penguins per group
dplyr::ungroup() # remove the still lingering grouping
```
Slicing is also the relevant operation to take random samples from the observations in a `tibble`.
```{r}
peng %>% dplyr::slice_sample(n = 10)
```
### Exercise
For this exercise we once more go back to the `mtcars` dataset.
See `?mtcars` for details.
1. Determine the number of cars with four _forward gears_ (`gear`) in the `mtcars` dataset.
```{r}
```
2. Determine the mean _1/4 mile time_ (`qsec`) per _Number of cylinders_ (`cyl`) group.
```{r}
```
3. Identify the least efficient (see `mpg`) cars for both _transmission types_ (`am`).
```{r}
```
::: {.callout-tip title="Possible solutions" collapse=true}
```{r}
mtcars %>%
dplyr::filter(gear == 4) %>%
nrow()
```
```{r}
mtcars %>%
dplyr::group_by(cyl) %>%
dplyr::summarise(
qsec_mean = mean(qsec)
)
```
```{r}
# make the care name an explicit column
mtcars2 <- tibble::rownames_to_column(mtcars, var = "car")
# Solution 1
mtcars2 %>%
dplyr::group_by(am) %>%
dplyr::arrange(mpg) %>%
dplyr::slice_head(n = 1) %$%
car
# Solution 1 only returns n = 1 result per group even if
# there are multiple cars with the same minimal mpg value.
# Solution 2 shows both, if this is desired.
# Solution 2
mtcars2 %>%
dplyr::group_by(am) %>%
dplyr::filter(mpg == min(mpg)) %$%
car
```
:::
## Transforming and manipulating tibbles
### Renaming and reordering columns with `rename` and `relocate`
Columns in tibbles can be renamed with `dplyr::rename`.
```{r}
peng %>% dplyr::rename(penguin_name = id) # rename a column
```
And with `dplyr::relocate` they can be reordered.
```{r}
peng %>% dplyr::relocate(year, .before = species) # reorder columns
```
### Adding columns to tibbles with `mutate` and `transmute`.
A common application of data manipulation is adding new, derived columns, that combine or modify the information in the already available columns. `dplyr` offers this core feature with the `mutate` function.
```{r}
peng %>%