-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtutorial_R_advanced.html
More file actions
889 lines (775 loc) · 46.5 KB
/
Copy pathtutorial_R_advanced.html
File metadata and controls
889 lines (775 loc) · 46.5 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
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Tidyverse Workflow</title>
<script src="site_libs/header-attrs-2.7/header-attrs.js"></script>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/sandstone.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<style>h1 {font-size: 34px;}
h1.title {font-size: 38px;}
h2 {font-size: 30px;}
h3 {font-size: 24px;}
h4 {font-size: 18px;}
h5 {font-size: 16px;}
h6 {font-size: 12px;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<link rel="stylesheet" href="style.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.tab('show');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row">
<div class="col-sm-12 col-md-4 col-lg-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-sm-12 col-md-8 col-lg-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">R</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="tutorial_R_basic.html">R Basic</a>
</li>
<li>
<a href="tutorial_R_advanced.html">Advanced R</a>
</li>
<li>
<a href="more_resources.html">More Resources</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">Tidyverse Workflow</h1>
</div>
<hr />
<p>Author: Henri Chung, Jia Liu</p>
<p>Date: 03/27/2021</p>
<hr />
<div id="packages-and-the-tidyverse." class="section level1" number="1">
<h1 number="1"><span class="header-section-number">1</span> Packages and The Tidyverse.</h1>
<p><br></p>
<p>In the first workshop, we focused on basic R functions that come natively with R. Although these functions are relatively simple, they can be combined and re-arranged in many different <em>functions</em> to perform a wide variety of analyses. However, knowing how and when to combine these functions can be difficult, and the resulting code can become difficult to understand and use. To make it easier to reuse and share R code, these functions are commonly written into <em>packages</em> and uploaded to the <strong>Comprehensive R Archive Network</strong> or CRAN. CRAN hosts a wide variety of specialized packages with specific functions for different analyses; time series, spatial, microbiome, sequence, etc.</p>
<p>Packages from CRAN can be downloaded and used as follows:</p>
<p>The <code>library()</code> function tells R to immediately make available any functions from the package for use. If you did not use <code>library()</code>, you would have to specify which package a command came from before using it. This is necessary to avoid situations where to packages have created functions with the same name. While loading the necessary packages prior to perform an analysis is relatively commonplace, relying on too many packages may lead to cases where you accidentally use a function from a different package than you intended.</p>
<pre class="r"><code>#run intersect from the dplyr package without first loading it.
across()
#tell R where the intersect function comes from with ::
dplyr::across()
#load the dplyr package first, and then use intersect
library(dplyr)
across()
#compare the function of base::intersect and dplyr::intersect
?intersect()</code></pre>
<p>Today, we’re going to be looking at a collection of packages known as the <strong>tidyverse</strong>. The tidyverse is a collection of “highly opinionated” packages for data manipulation and analysis in R. The tidyverse relies on a set of “tidy” data principles, which are rules for the way that data should be formatted and organized prior to analysis. This usually requires users to reformat their data into a “tidy” format as a necessary step before performing the analysis. If you agree with the tidy principles, following these steps may be an obvious and necessary step. Although there is a sizable group of R users that think these requirements are tedious. Regardless of who is right, the tidyverse is one of the most commonly used packages in R and many R users have come to rely on their functions.</p>
<p>In order for data to be tidy, it must be:</p>
<ul>
<li>Each variable must have its own column.</li>
<li>Each observation must have its own row.</li>
<li>Each value must have its own cell.</li>
</ul>
<p><br></p>
</div>
<div id="import-data-to-r" class="section level1" number="2">
<h1 number="2"><span class="header-section-number">2</span> Import data to R</h1>
<p><br></p>
<p>Let’s start by importing some data into R. We will be looking at a dataset of greenhouse emission from agricultural area of European countries during Year <span class="math inline">\(1990\)</span>-<span class="math inline">\(2006\)</span>. The original dataset was downloaded from the <a href="https://data.europa.eu/euodp/en/data/dataset?q=air+emission&vocab_catalog=http%3A%2F%2Fdata.europa.eu%2F88u%2Fcatalog%2Feuodp&ext_boolean=all&sort=">European Union Open Data Portal</a>. I have already reorganized this data into a tidy format.</p>
<p>Before talking about how to access values in such dataframes, let’s first see how we can import a dataset into R: We will use the <code>utils::read.table</code> function.</p>
<pre class="r"><code>#read in the greenhouse gas data.
ghg <- utils::read.table("data/europ_agriculture_GHG.csv", header = TRUE, sep = ",")
#read.csv
ghg <- utils::read.csv("data/europ_agriculture_GHG.csv", header = TRUE)
#read.tsv
#ghg <- utils::read.table("data/europ_agriculture_GHG.csv", header = TRUE, sep = "\t")
#ghg <- utils::read.tsv("data/europ_agriculture_GHG.csv", header = TRUE)</code></pre>
<p><br></p>
<p>Let’s take a quick look at the data:</p>
<pre class="r"><code># return the first 6 rows of the object which is dataframe "ghg" here
head(ghg)</code></pre>
<pre><code>## Country_code Country Sector_code Sector Pollutant Year Value Units
## 1 AT Austria 4 Agriculture CH4 1990 230015.5 Mg
## 2 AT Austria 4 Agriculture CH4 1991 226798.0 Mg
## 3 AT Austria 4 Agriculture CH4 1992 218327.0 Mg
## 4 AT Austria 4 Agriculture CH4 1993 218808.7 Mg
## 5 AT Austria 4 Agriculture CH4 1994 219121.4 Mg
## 6 AT Austria 4 Agriculture CH4 1995 220144.6 Mg</code></pre>
<pre class="r"><code># return the last 6 rows.
tail(ghg)</code></pre>
<pre><code>## Country_code Country Sector_code Sector Pollutant Year Value Units
## 2171 TR Turkey 4 Agriculture N2O 2001 424.0000 Mg
## 2172 TR Turkey 4 Agriculture N2O 2002 444.0000 Mg
## 2173 TR Turkey 4 Agriculture N2O 2003 438.0000 Mg
## 2174 TR Turkey 4 Agriculture N2O 2004 484.0000 Mg
## 2175 TR Turkey 4 Agriculture N2O 2005 510.2228 Mg
## 2176 TR Turkey 4 Agriculture N2O 2006 510.2228 Mg</code></pre>
<pre class="r"><code># return the dimensions
dim(ghg)</code></pre>
<pre><code>## [1] 2176 8</code></pre>
<pre class="r"><code># return the number of rows
nrow(ghg)</code></pre>
<pre><code>## [1] 2176</code></pre>
<pre class="r"><code># return the number of columns
ncol(ghg)</code></pre>
<pre><code>## [1] 8</code></pre>
<pre class="r"><code>#View the ghg table as a separate window
#View()</code></pre>
<blockquote>
<p>Notice that the datasets you work with in practical may not be clean, for example, there maybe missing values. <a href="https://uc-r.github.io/missing_values">Here</a> is a link that talks about how to deal with missing values in R. You may find more solutions or suggestions online.</p>
</blockquote>
<p><br></p>
</div>
<div id="data-wrangling-with-tidyverse" class="section level1" number="3">
<h1 number="3"><span class="header-section-number">3</span> Data wrangling with <code>tidyverse</code></h1>
<p><br></p>
<p>The first tidyverse package we’ll look at is <code>dplyr</code> (pronounced “d-plier”), which provides basic functions for data manipulation. These functions can be categorized based on how they operate on a table.</p>
<ul>
<li>Rows
<ul>
<li><code>filter()</code> chooses rows based on column values.</li>
<li><code>slice()</code>chooses rows based on location.</li>
<li><code>arrange</code> changes the order of the rows.</li>
</ul></li>
<li>Columns
<ul>
<li><code>select</code> changes whether or not a column is selected.</li>
<li><code>rename</code> changes the name of the columns.</li>
<li><code>mutate</code> changes the values of the columns and creates new columns.</li>
</ul></li>
<li>Groups of rows:
<ul>
<li><code>summarise</code> collapses a group into a single row.</li>
</ul></li>
</ul>
<p>Lets look at each of the functions in an example.</p>
<hr />
<p><br></p>
<div id="filter-rows-based-on-column-values." class="section level2" number="3.1">
<h2 number="3.1"><span class="header-section-number">3.1</span> <strong>Filter</strong> rows based on column values.</h2>
<p>The <code>filter</code> function allows us to choose specific parts of our data to look at based on the values of certain variables. We would use this function to answer questions such as; “What were the emissions after the year 2000?” or “What were the total emissions produced by the country Belgium?”.</p>
<pre class="r"><code>#filter year > 2000
ghg_post2005 <- filter(ghg, Year > 2000)
#filter on country = belgium
ghg_belgium <- filter(ghg, Country == "Belgium")</code></pre>
<p>We can also combine multiple filter commands together using AND/OR expressions.</p>
<pre class="r"><code>#AND with &
ghg_2005andbelgium <- filter(ghg, Year == 2005 & Country == "Belgium")
#OR with |
ghg_2005or2006 <- filter(ghg, Year == 2005 | Year == 2006)</code></pre>
<p><strong>Question: Why do we need to use <code>==</code> instead of <code>=</code>?</strong></p>
<p><br></p>
</div>
<div id="slice-rows-based-on-location." class="section level2" number="3.2">
<h2 number="3.2"><span class="header-section-number">3.2</span> <strong>Slice</strong> rows based on location.</h2>
<p>The <code>slice</code> function cuts out rows of the data based on its numerical position in the table. We would use this function if we wanted to look at rows 20:40 in the dataset. Slice also comes with several helper functions to take out different arrangements of the dataset.</p>
<pre class="r"><code>#slice out rows 20:40
ghg_20to40 <- slice(ghg, 20:40)
#slice out the first 10 rows.
ghg_first10 <- slice_head(ghg, n = 10)
#slice out the last 10 rows.
ghg_last10 <- slice_tail(ghg, n = 10)
#take a random sample slice of 10 rows.
ghg_sample10 <- slice_sample(ghg, n = 10)</code></pre>
<p><strong>Question: How would you use slice to take every 10th row in the dataset? (row 10, 20, 30, etc)</strong></p>
<p><br></p>
</div>
<div id="arrange-the-rows-into-a-specific-order." class="section level2" number="3.3">
<h2 number="3.3"><span class="header-section-number">3.3</span> <strong>Arrange</strong> the rows into a specific order.</h2>
<p>The <code>arrange</code> function allows to move around the rows of the data into a specific order. This function is typically used when we want to sort the data based on a specific column value. For example, “Re-arrange the rows so that the highest emission values come first.” or “Re-arrange the rows first by highest emissions, then by country”.</p>
<pre class="r"><code>#arrange by country
ghg_bycountry <- arrange(ghg, Country)
#arrange by country and emission values
ghg_bycountry_emissions <- arrange(ghg, Value)
#arrange by country and descending emission values
ghg_bycountry_descemissions <- arrange(ghg, desc(Value))</code></pre>
<p><br></p>
</div>
<div id="select-columns-by-name." class="section level2" number="3.4">
<h2 number="3.4"><span class="header-section-number">3.4</span> <strong>Select</strong> columns by name.</h2>
<p>The <code>select</code> function is used to choose specific columns of the data based on their column name. This is useful when the data has many columns but you are only interested in specific ones. The other columns may not contain useful information or you might not want to look at the information for a specific analysis. For example, in our ghg dataset, the <code>Sector_code</code> and <code>Country_code</code> columns are not very useful because we are not familiar with their code system. If we wanted to know what sector the data was from, we could use the more descriptive <code>Sector</code> or <code>Country</code> columns.</p>
<pre class="r"><code>#select the Country and Value column's from the data.
ghg_country_value <- select(ghg, c("Country", "Value"))
#select every column except the Sector_code column.
ghg_nocode <- select(ghg, -c("Sector_code", "Country_code"))</code></pre>
<blockquote>
<p><a href="https://suzan.rbind.io/2018/01/dplyr-tutorial-1/#selecting-columns-the-basics">More</a> options for selecting columns.</p>
</blockquote>
<p><br></p>
</div>
<div id="rename-columns-to-a-different-name." class="section level2" number="3.5">
<h2 number="3.5"><span class="header-section-number">3.5</span> <strong>Rename</strong> columns to a different name.</h2>
<p>The <code>rename</code> function is to change the name of specific columns. One common usecase for the <code>rename</code> function is when you are working across multiple datasets with different names for the same column variable. For example, the column for <code>country</code> may be named <code>Country</code> in one table and <code>country</code> in another. These values in these two columns mean the same thing, but the slightly different capitalization would make it annoying to work back and forth between both. We can use the <code>rename</code> function to change the names so that they are the same.</p>
<pre class="r"><code>#rename "Country" column to "country", notice the syntax in the command is reversed.
ghg_renamed <- rename(ghg, country = Country)
colnames(ghg_renamed)</code></pre>
<pre><code>## [1] "Country_code" "country" "Sector_code" "Sector" "Pollutant" "Year"
## [7] "Value" "Units"</code></pre>
<pre class="r"><code>#We can rename multiple columns at once.
ghg_renamed2 <- rename(ghg, country = Country, year = Year)</code></pre>
<p><br></p>
</div>
<div id="mutate-columns-to-a-new-value." class="section level2" number="3.6">
<h2 number="3.6"><span class="header-section-number">3.6</span> <strong>Mutate</strong> columns to a new value.</h2>
<p>The <code>mutate</code> function can be used to change the values within a column or to create a new column based on a previous column. In our ghg dataset, the numbers in the dataset are in Mg or ‘Megagrams’, but what if we wanted our values in Kilograms (Kg) or Gigagrams? (Gg). We can either change the columns in place or create new columns to represent these values.</p>
<pre class="r"><code>#change values and units to kilograms in place.
ghg_kg <- mutate(ghg, Value = Value*1000, Unit = "kg")
#create new column for value and units in gigagrams.
ghg_gg <- mutate(ghg, Value2 = Value/1000, Unit2 = "Gg")</code></pre>
<p><strong>Excerise: The <code>tolower()</code> function converts all of the characters in a string to lowercase. Use the <code>tolower()</code> and <code>mutate()</code> to change all of the values int he Country column to lowercase.</strong></p>
<p><br></p>
</div>
<div id="summarise-the-data-by-column-and-row-values." class="section level2" number="3.7">
<h2 number="3.7"><span class="header-section-number">3.7</span> <strong>Summarise</strong> the data by column and row values.</h2>
<p>The <code>Summarise</code> function allows us to calculate different summary statistics on the dataset in a single step. We use <code>summarise</code> to answer questions like; “What was the average emission value?”, What about the standard deviation, maximum, or minumum values? When combined with the <code>group_by</code> function, we can calculate these values for specific subgroups of the data in a single step.</p>
<pre class="r"><code>ghg_summary = summarise(ghg, mean = mean(Value), sd = sd(Value), min = min(Value), max = max(Value))
ghg_summary_country <- summarise( group_by(ghg, Country), mean = mean(Value), sd = sd(Value), min = min(Value), max = max(Value))</code></pre>
<p><strong>Exercise: How would you find the mean value for emissions per year?</strong></p>
<p><br></p>
</div>
<div id="combining-functions-and-the-pipe" class="section level2" number="3.8">
<h2 number="3.8"><span class="header-section-number">3.8</span> Combining Functions and the Pipe <code>%>%</code></h2>
<p>Now that we understand the basic functions, we can start combining them in order to analyze our data. For example, what if we wanted to know which countries had the highest average greenhouse gas emissions? We would use a combination of the <code>group_by()</code>, <code>summarise()</code> and <code>arrange()</code> functions.</p>
<pre class="r"><code>grouped_ghg <- group_by(ghg, Country)
summarised_ghg <- summarise(grouped_ghg, mean = mean(Value))
arranged_ghg <- arrange(summarised_ghg, desc(mean))</code></pre>
<p>The result we wanted is in arranged_ghg, but we have also created the <code>grouped_ghg</code> and <code>summarised_ghg</code> tables as part of our analysis. While these tables were necessary to get our final result, we don’t need to keep them around anymore. We can remove them from our workspace with the <code>rm</code> function, but that can get tedious if there are multiple table. Creating additional objects can also make the code look cluttered and difficult to read. To remedy this, tidyverse functions includes support for a pipe operator <code>%>%</code>. The pipe operator “pipes” the output of one function into another. Using the pipe, we can rewrite the previous chunk as follows.</p>
<pre class="r"><code>arrange_ghg2 <- ghg %>%
group_by(Country) %>%
summarise(mean = mean(Value)) %>%
arrange(desc(mean))</code></pre>
<p>Using the pipe, we avoid creating unnecessary additional objects and additional lines of code, while making the code easier to read and follow.</p>
<blockquote>
<p>The pipe operator <code>%>%</code> does not actually manipulate objects in place. The pipe actually creates an additional object behind the scenes, deleted the original, and then renames and returns the additional table. This means that while the pipe operator is useful for keeping your workspace clean, it does not help if you are limited in the number of objects you can create in your computers memory.</p>
</blockquote>
<p><br></p>
<div id="exercise" class="section level3" number="3.8.1">
<h3 number="3.8.1"><span class="header-section-number">3.8.1</span> Exercise</h3>
<ul>
<li><p>Using <code>ghg</code> as your input data, complete the following operations. You do not have to use <code>%>%</code>, but are encouraged to do so. The exercises will get progressively more difficult, you do not have to complete all of the questions.</p>
<ul>
<li>Take <code>ghg</code> data, select columns <code>Country</code>, <code>Pollutant</code>, <code>Year</code>, <code>Value</code> with <code>select</code> function.</li>
<li>Filter out rows with <code>Pollutant == N2O</code>.</li>
<li>Rename all of the columns to lowercase using the <code>rename</code> function.</li>
<li>Assign the values for the emissions of N20 to <code>N2O_ghg</code> (Hint: use <code><-</code> to assign value to variable).</li>
<li>Summarise the average CO2 emission values for each country using the <code>filter</code>, <code>group_by</code>, and <code>summarise</code> functions.</li>
<li>The <code>pull</code> function extracts the values of a column of a dataframe and puts it into a vector. Using the <code>select</code>, <code>pull</code> and <code>unique</code> functions, determine how many countries are included in the dataset.</li>
<li>Using the <code>group_by</code> and <code>summarise</code> functions to find out which greenhouse gas emission has the highest standard deviation.</li>
<li>Using the <code>filter</code>, <code>group_by</code> and <code>summarise</code> functions to find out which countries had the highest CH4 emission for from 1995 to 2000.</li>
</ul></li>
</ul>
<p><br></p>
<p><strong>Solutions</strong></p>
<pre class="r"><code># 1
ex1 <- select (ghg, Country, Pollutant, Year, Value)
# 2
ex2 <- filter (ghg, Pollutant == "N2O")
# 3
ex3 <- rename_all (ghg, tolower)
# 4
ex4 <- filter(ghg, Pollutant == "N2O")
N2O_ghg <- ex4$Value
# 5
ex5 <- ghg %>%
filter(Pollutant == "CO2") %>%
group_by(Country) %>%
summarise(mean = mean(Value))
# 6
ex6 <- ghg %>%
select (Country) %>%
pull (Country) %>%
unique()
# 7
ex7 <- ghg %>%
group_by(Pollutant) %>%
summarise(sd = sd(Value)) %>%
ungroup() %>%
arrange(desc(sd))
# 8
ex8 <- ghg %>%
filter(Year >= 1995 & Year <= 2000) %>%
filter(Pollutant == "CH4") %>%
group_by(Country) %>%
summarise(mean = mean(Value)) %>%
ungroup() %>%
arrange(desc(mean))</code></pre>
<p><br></p>
</div>
</div>
</div>
<div id="visualizing-data-with-ggplot2" class="section level1" number="4">
<h1 number="4"><span class="header-section-number">4</span> Visualizing data with <code>ggplot2</code></h1>
<p><br></p>
<p>The dplyr functions are extremely useful for calculating summary statistics on the tables. However, sometimes relationships are more easily understood by plotting and visualiizing the data in a graph. Similar to the <code>tidy</code> principles for data organization, the authors of the tidyverse believe in a very specific <a href="https://vita.had.co.nz/papers/layered-grammar.html">philosophy</a> for creating graphs and other data visualizations. This philosophy and the functions that work with it are encompassed in the <code>ggplot2</code> package.</p>
<p>In <code>ggplot2</code> every graph is composed of multiple different <em>mappings</em>. To create a graph, you must first start by placing down a base layer, and iteratively adding more and more mappings to it to specify the design and layout of your graph. This is analogous to our data analysis steps from before, where an analysis was built by applying multiple functions in a row with <code>%>%</code>.</p>
<p>Let’s start by building a basic graph that shows how CH4 emissions have increased over time in Austria. First, we must subset our data of interest.</p>
<pre class="r"><code>ghg2 <- ghg %>%
filter(Country == "Austria" & Pollutant == "CH4")
ghg2</code></pre>
<pre><code>## Country_code Country Sector_code Sector Pollutant Year Value Units
## 1 AT Austria 4 Agriculture CH4 1990 230015.5 Mg
## 2 AT Austria 4 Agriculture CH4 1991 226798.0 Mg
## 3 AT Austria 4 Agriculture CH4 1992 218327.0 Mg
## 4 AT Austria 4 Agriculture CH4 1993 218808.7 Mg
## 5 AT Austria 4 Agriculture CH4 1994 219121.4 Mg
## 6 AT Austria 4 Agriculture CH4 1995 220144.6 Mg
## 7 AT Austria 4 Agriculture CH4 1996 216805.6 Mg
## 8 AT Austria 4 Agriculture CH4 1997 213784.0 Mg
## 9 AT Austria 4 Agriculture CH4 1998 212922.0 Mg
## 10 AT Austria 4 Agriculture CH4 1999 208821.8 Mg
## 11 AT Austria 4 Agriculture CH4 2000 206616.4 Mg
## 12 AT Austria 4 Agriculture CH4 2001 204444.5 Mg
## 13 AT Austria 4 Agriculture CH4 2002 200088.8 Mg
## 14 AT Austria 4 Agriculture CH4 2003 198537.5 Mg
## 15 AT Austria 4 Agriculture CH4 2004 196893.0 Mg
## 16 AT Austria 4 Agriculture CH4 2005 195704.3 Mg
## 17 AT Austria 4 Agriculture CH4 2006 194993.8 Mg</code></pre>
<p>Now that we have our data, we can start working on our plot. In the first layer of our plot, we must declare the <code>aesthetics</code> or what variables we want to map to specific parts of our base layer. In most cases, this first means specifying which aspects of our data are going to be our X-axis and our Y-axis. If we want to visualize the relationship of CH4 emissions over time, what would our X-axis and Y-axis be?</p>
<pre class="r"><code>#we tell ggplot our intended mappings with the aesthetics function (confusing I know)
ghg2_plot <- ggplot(ghg2, aes(x = Year, y = Value))
ghg2_plot</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-18-1.png" width="672" /></p>
<p><br></p>
<div id="geoms" class="section level2" number="4.1">
<h2 number="4.1"><span class="header-section-number">4.1</span> <code>Geoms</code></h2>
<p>Our plot now consists of a base layer! As you can see, ggplot has correctly labeled the X and Y axis with what we told it. However, the graph is missing <code>geoms</code> (short for geometric_elements), or the name of the object to draw each observation. A <code>geom</code> may be a point (scatterplot), a line (line plot), or a bar (bar plot).</p>
<pre class="r"><code>#scatterplot
ghg2_plot_scatter <- ggplot(ghg2, aes(x = Year, y = Value)) + geom_point()
ghg2_plot_scatter</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-19-1.png" width="672" /></p>
<pre class="r"><code>#lineplot
ghg2_plot_line <- ghg2_plot + geom_line()
ghg2_plot_line</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-20-1.png" width="672" /></p>
<pre class="r"><code>#barplot
ghg2_plot_bar <- ghg2_plot + geom_bar(stat = "identity")
ghg2_plot_bar</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-21-1.png" width="672" /></p>
<p>Some <code>geoms</code> can be used to perform additional analysis on the data. The <code>geom_smooth</code> function fits a smooth line to the data following a specific formula. We can use the <code>geom_smooth</code> function to plot the slope of the line using a linear model.</p>
<pre class="r"><code>#plot smooth line with linear model
ghg2_plot_lm <- ggplot(ghg2, aes(x = Year, y = Value)) + geom_smooth(method = "lm")
ghg2_plot_lm</code></pre>
<pre><code>## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-22-1.png" width="672" /></p>
<pre class="r"><code>#plot smooth line with Local regression (loess)
ghg2_plot_loess <- ggplot(ghg2, aes(x = Year, y = Value)) + geom_smooth(method = "loess")
ghg2_plot_loess</code></pre>
<pre><code>## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-23-1.png" width="672" /></p>
<pre class="r"><code>#we can also stack multiple geoms on top of each other.
ghg2_plot_combo <- ggplot(ghg2, aes(x = Year, y = Value)) + geom_point() + geom_line()
ghg2_plot_combo</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-24-1.png" width="672" /></p>
<p><br></p>
</div>
<div id="scales---color-size-and-shape" class="section level2" number="4.2">
<h2 number="4.2"><span class="header-section-number">4.2</span> <code>Scales</code> - Color, Size, and Shape</h2>
<p>Once we have a basic plot, we can start specifying additional specifications call <code>scales</code>. <code>Scales</code> map values from the data to aesthetics such as <code>color</code>, <code>size</code>, and <code>shape</code> to customize our plot. These <code>scales</code> can be input in two ways, either as a single value or varying with a specific variable. To visualize this, we will recreate our previous graph but include additional countries in addition to Austria. We will use the <code>%in%</code> operator to specify what countries we want to include. We can separate the different countries by specificing a <code>group</code> aesthetic.</p>
<pre class="r"><code>ghg3_plot <- ghg %>%
filter(Pollutant == "CH4" & Country %in% c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")) %>%
ggplot(aes(x = Year, y = Value, group = Country)) + geom_point() + geom_line()
ghg3_plot</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-25-1.png" width="672" /></p>
<p>Specifying a specific color.</p>
<pre class="r"><code>ghg3_plot1 <- ghg %>%
filter(Pollutant == "CH4"& Country %in% c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")) %>%
ggplot(aes(x = Year, y = Value, group = Country)) + geom_point(color = "red") + geom_line(color = "red")
ghg3_plot1</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-26-1.png" width="672" /> Specifying a color mapping to a variable.</p>
<pre class="r"><code>ghg3_plot2 <- ghg %>%
filter(Pollutant == "CH4" & Country %in% c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")) %>%
ggplot(aes(x = Year, y = Value, group = Country, color = Country)) + geom_point() + geom_line()
ghg3_plot2</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-27-1.png" width="672" /> If we only want to color the points or the lines, We can also specify colors inside specific <code>geoms</code></p>
<pre class="r"><code>ghg3_plot3 <- ghg %>%
filter(Pollutant == "CH4" & Country %in% c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")) %>%
ggplot(aes(x = Year, y = Value, group = Country)) + geom_point(aes(color = Country)) + geom_line()
ghg3_plot3</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-28-1.png" width="672" /></p>
<pre class="r"><code>ghg3_plot5 <- ghg %>%
filter(Pollutant == "CH4"& Country %in% c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")) %>%
ggplot(aes(x = Year, y = Value, group = Country)) + geom_point() + geom_line(aes(color = Country))
ghg3_plot5</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-29-1.png" width="672" /></p>
<p>We can improve the readability of the plot by making the points drawn by <code>geom_point()</code> smaller.</p>
<pre class="r"><code>ghg3_plot5 <- ghg %>%
filter(Pollutant == "CH4" & Country %in% c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")) %>%
ggplot(aes(x = Year, y = Value, group = Country, color = Country)) + geom_point(size = 1) + geom_line()
ghg3_plot5</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-30-1.png" width="672" /></p>
<p>Similiar to size and color, we can also specific different shapes to each of our</p>
<pre class="r"><code>ghg3_plot4 <- ghg %>%
filter(Pollutant == "CH4" & Country %in% c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")) %>%
ggplot(aes(x = Year, y = Value, group = Country, color = Country)) + geom_point(size = 1, aes(shape = Country))
ghg3_plot4</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-31-1.png" width="672" /></p>
<p><br></p>
</div>
<div id="labels-and-scales" class="section level2" number="4.3">
<h2 number="4.3"><span class="header-section-number">4.3</span> Labels and Scales</h2>
<p>So far, our graphs look good. But without proper labeling, it can hard for a view to understand the graph. To complete the graph, we must add proper scale labels and titles to our plot. We will add the proper labels to our graph with the <code>labs()</code> function.</p>
<pre class="r"><code>ghg3_plot5 <- ghg %>%
filter(Pollutant == "CH4" & Country %in% c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")) %>%
ggplot(aes(x = Year, y = Value, group = Country, color = Country)) + geom_point(size = 1, aes(shape = Country)) +
labs(title = "CO2 Emissions for Several European Countries", y = "CO2 Emissions (Mg)")
ghg3_plot5</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-32-1.png" width="672" /></p>
<p>The <code>labs()</code> function also has arguments for <code>captions</code> and <code>subtitles</code>.</p>
<pre class="r"><code>ghg3_plot6 <- ghg %>%
filter(Pollutant == "CH4" & Country %in% c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")) %>%
ggplot(aes(x = Year, y = Value, group = Country, color = Country)) + geom_point(size = 1, aes(shape = Country)) +
labs(title = "CO2 Emissions for Several European Countries", y = "CO2 Emissions (Mg)", subtitle = "by HC", caption = "Example plot 6 for BCB R workshop")
ghg3_plot6</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-33-1.png" width="672" /></p>
<p><br></p>
</div>
<div id="faceting-and-themes" class="section level2" number="4.4">
<h2 number="4.4"><span class="header-section-number">4.4</span> Faceting and Themes</h2>
<p><code>Faceting</code> is a way to create multiple subplots of your data in a single command. This allows you to rapidly compare patterns in different parts of the data to see if they are the same or different. There are two ways to facet a graph, <code>facet_wrap</code> and <code>facet_grid</code>. <code>facet_wrap</code> will create multiple subplots and place them in order rowise, while <code>facet_grid</code> will snap the subplots to a predetermined grid. The easiest way to see the difference is with an example.</p>
<pre class="r"><code>countries = c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")
years = c(2000, 2001, 2002, 2003, 2004, 2005)
ghg3_plot7 <- ghg %>%
filter(Pollutant == "CH4" & Country %in% countries & Year %in% years) %>%
ggplot(aes(x = Year, y = Value, group = Country, color = Country)) + geom_point(size = 1, aes(shape = Country)) +
labs(title = "CO2 Emissions for Several European Countries", y = "CO2 Emissions (Mg)", subtitle = "by HC", caption = "Example plot 6 for BCB R workshop") +
facet_wrap(~Country)
ghg3_plot7</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-34-1.png" width="672" /></p>
<pre class="r"><code>countries = c("Austria", "Belgium")
years = c(2000, 2001, 2002)
ghg3_plot8 <- ghg %>%
filter(Pollutant == "CH4" & Country %in% countries & Year %in% years) %>%
ggplot(aes(x = as.factor(Year), y = Value, group = Country, color = Country)) + geom_point(size = 1, aes(shape = Country)) +
labs(title = "CO2 Emissions for Several European Countries", y = "CO2 Emissions (Mg)", x = "Year", subtitle = "by HC", caption = "Example plot 6 for BCB R workshop") +
facet_wrap(Year~Country)
ghg3_plot8</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-35-1.png" width="672" /></p>
<p><strong>What effect does changing <code>x = Year</code> to <code>x = as.factor(Year)</code> have on the graph?</strong></p>
<pre class="r"><code>countries = c("Austria", "Belgium")
years = c(2000, 2001, 2002)
ghg3_plot8 <- ghg %>%
filter(Pollutant == "CH4" & Country %in% countries & Year %in% years) %>%
ggplot(aes(x = as.factor(Year), y = Value, group = Country, color = Country)) + geom_point(size = 1, aes(shape = Country)) +
labs(title = "CO2 Emissions for Several European Countries", y = "CO2 Emissions (Mg)", x = "Year", subtitle = "by HC", caption = "Example plot 6 for BCB R workshop") +
facet_grid(Year~Country)
ghg3_plot8</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-36-1.png" width="672" /> Lastly, we can change the look and feel of our plots using <code>themes</code>. <code>Themes</code> apply a bunch of specific plot specifications at once to create a single overall “look” for your graph. This means that if you wanted, you could recreate a <code>theme</code> on your own by specifying each individual part of your graph, but often it is easier to use a pre-written theme to create a single look. There are many themes available in ggplot, and some artistic R users create their own themes and upload them as packages for others to use. Below, we look at the effect of a couple included themes in R.</p>
<p>Black and White</p>
<pre class="r"><code>countries = c("Austria", "Belgium", "Cyprus", "Denmark", "Estonia", "Finland")
years = c(2000, 2001, 2002, 2003, 2004)
ghg3_plot9 <- ghg %>%
filter(Pollutant == "CH4" & Country %in% countries & Year %in% years) %>%
ggplot(aes(x = as.factor(Year), y = Value, group = Country, color = Country)) + geom_point(size = 1, aes(shape = Country)) +
labs(title = "CO2 Emissions for Several European Countries", y = "CO2 Emissions (Mg)", x = "Year", subtitle = "by HC", caption = "Example plot 6 for BCB R workshop") +
facet_wrap(~Country)
ghg3_plot9 + theme_bw()</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-37-1.png" width="672" /> Minimal</p>
<pre class="r"><code>ghg3_plot9 + theme_minimal()</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-38-1.png" width="672" /> Classic</p>
<pre class="r"><code>ghg3_plot9 + theme_classic()</code></pre>
<p><img src="tutorial_R_advanced_files/figure-html/unnamed-chunk-39-1.png" width="672" /></p>
<p><br></p>
</div>
<div id="exercise-1" class="section level2" number="4.5">
<h2 number="4.5"><span class="header-section-number">4.5</span> Exercise</h2>
<p>This <a href="http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html">link</a> contains a list of many of the possible plots you can make with ggplot. Using the link and the <code>ghg</code> data, make a plot that answers a question about the data. Here are some examples:</p>
<ul>
<li>Which countries have the highest CO2 emissions in 2002?</li>
<li>Is the emissions for the <code>GWP</code> pollutant increasing or decreasing over time?</li>
<li>What year had the highest <code>CO2</code> emissions?</li>
<li>Visualize the average level of each pollutant produced by each country.</li>
<li>For each pollutant, find the country and year in which the emissions were highest.</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.odd').parent('tbody').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
$(document).ready(function () {
$('.tabset-dropdown > .nav-tabs > li').click(function () {
$(this).parent().toggleClass('nav-tabs-open');
});
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')
.removeClass('toc-ignore')
.children('h1,h2,h3,h4,h5').addClass('toc-ignore');
// establish options
var options = {
selectors: "h1,h2,h3",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_');
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = true;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>