This repository has been archived by the owner on Jan 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
wk05_joining.html
623 lines (580 loc) · 29.8 KB
/
wk05_joining.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta name="author" content="Ben Best" />
<meta name="date" content="2016-01-29" />
<title>joining</title>
<script src="libs/jquery-1.11.0/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="libs/bootstrap-3.3.1/css/cosmo.min.css" rel="stylesheet" />
<script src="libs/bootstrap-3.3.1/js/bootstrap.min.js"></script>
<script src="libs/bootstrap-3.3.1/shim/html5shiv.min.js"></script>
<script src="libs/bootstrap-3.3.1/shim/respond.min.js"></script>
<!-- http://www.favicon-generator.org/ -->
<link rel="apple-touch-icon" sizes="57x57" href="favicons/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="favicons/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="favicons/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="favicons/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="favicons/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="favicons/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="favicons/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="favicons/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="favicons/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="favicons/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="favicons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="favicons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="favicons/favicon-16x16.png">
<link rel="manifest" href="favicons/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="../favicons/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
<link href="libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet">
<script src="libs/tocify-1.9.1/jquery-ui-1.9.2.custom.min.js"></script>
<script src="libs/tocify-1.9.1/jquery.tocify.min.js"></script>
<link href="libs/lightbox-2.8.2/css/lightbox.min.css" rel="stylesheet">
<!--
Font Awesome: http://fortawesome.github.io/Font-Awesome/icons
Octicons: https://octicons.github.com
-->
<link rel="stylesheet" href="libs/font-awesome-4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="libs/octicons-3.3.0/octicons.css">
<style type="text/css">
@media (max-width: 992px) {
#toc {
position: relative;
width: 100%;
margin: 0px 0px 20px 0px;
}
}
</style>
<style type="text/css">code{white-space: pre;}</style>
<link rel="stylesheet"
href="libs/highlight/textmate.css"
type="text/css" />
<script src="libs/highlight/highlight.js"></script>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs && document.readyState && document.readyState === "complete") {
window.setTimeout(function() {
hljs.initHighlighting();
}, 0);
}
</script>
<link rel="stylesheet" href="libs/font-awesome-4.5.0/css/font-awesome.min.css" type="text/css" />
<link rel="stylesheet" href="libs/octicons-3.3.0/octicons.css" type="text/css" />
<link rel="stylesheet" href="styles/styles.css" type="text/css" />
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
height: auto;
}
</style>
<div class="container-fluid main-container">
<!--- https://codepo8.github.io/css-fork-on-github-ribbon/
<style>#forkongithub a{background:#000;color:#fff;text-decoration:none;font-family:arial,sans-serif;text-align:center;font-weight:bold;padding:5px 40px;font-size:1rem;line-height:2rem;position:relative;transition:0.5s;}#forkongithub a:hover{background:#c11;color:#fff;}#forkongithub a::before,#forkongithub a::after{content:"";width:100%;display:block;position:absolute;top:1px;left:0;height:1px;background:#fff;}#forkongithub a::after{bottom:1px;top:auto;}@media screen and (min-width:800px){#forkongithub{position:fixed;display:block;top:0;left:0;width:200px;overflow:hidden;height:200px;z-index:9999;}#forkongithub a{width:200px;position:absolute;top:60px;left:-60px;transform:rotate(-45deg);-webkit-transform:rotate(-45deg);-ms-transform:rotate(-45deg);-moz-transform:rotate(-45deg);-o-transform:rotate(-45deg);box-shadow:4px 4px 10px rgba(0,0,0,0.8);}}</style><span id="forkongithub"><a href="https://github.com/ucsb-bren/env-info">Fork me on GitHub</a></span>
-->
<div class="row-fluid">
<div class="navbar navbar-default navbar-fixed-top navbar-transparent">
<div class="container">
<div class="navbar-header">
<a href="http://ucsb-bren.github.io/env-info/" class="navbar-brand"><i class="fa fa-home"></i> env-info</a>
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse" id="navbar-main">
<!--
<ul class="nav navbar-nav">
<li>
<a href="/#schedule"><i class="fa fa-calendar"></i> schedule</a>
</li>
</ul>
-->
<ul class="nav navbar-nav navbar-right">
<li><a href="/students"><i class="fa fa-users"></i> students</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span3 col-md-3">
<div id="toc"></div>
</div>
<div class="main-content span9 col-md-9">
<div id="header">
<h1 class="title">joining</h1>
<h4 class="author"><em>Ben Best</em></h4>
<h4 class="date"><em>January 29, 2016</em></h4>
</div>
<div id="precursors" class="section level2">
<h2>Precursors</h2>
<div id="rstudio-heroes" class="section level3">
<h3>RStudio Heroes</h3>
<p>Last weekend at 1st annual <a href="https://www.rstudio.com/shinydevcon/">shinydevcon</a>. Left to right, <span class="citation">@github</span> (affiliation):</p>
<ul>
<li>Winston Chang <span class="citation">@wch</span> (RStudio)</li>
<li>Hadley Wickham <span class="citation">@hadley</span> (RStudio)</li>
<li>Julie Lowndes <span class="citation">@jules32</span> (OHI)</li>
<li>Jamie Afflerbach <span class="citation">@jafflerbach</span> (OHI)</li>
<li>Joe Cheng <span class="citation">@jcheng5</span> (RStudio)</li>
<li>Ben Best <span class="citation">@bbest</span> (OHI)</li>
<li>Herman Strop <span class="citation">@FrissAnalytics</span> (FrissAnalytics)</li>
</ul>
<div class="figure">
<img src="wk05_ggplot/img/rstudio_shinydevcon_wch-hadley-jcheng5-FrissAnalytics.JPG" alt="" />
</div>
<p>Brought some of these stickers for ya:</p>
<p><a href="https://www.rstudio.com/about/gear/"><img src="wk05_ggplot/img/rstudio_stickers.png" alt="" /></a></p>
</div>
<div id="rstudio-shortcuts" class="section level3">
<h3>RStudio Shortcuts</h3>
<ul>
<li><a href="./refs/cheatsheets/rstudio-IDE-cheatsheet.pdf">rstudio-IDE-cheatsheet.pdf</a>
<ul>
<li>Show Keyboard Shortcuts <code>?</code>: Alt+Shift+<strong>K</strong> (Win), Option+Shift+<strong>K</strong> (Mac)</li>
<li>(Un)Comment lines <code>#</code>: Ctrl+Shift+<strong>C</strong> (Win), Cmd+Shift+<strong>C</strong> (Mac)</li>
<li>Insert <code>%>%</code>: Ctrl+Shift+<strong>M</strong> (Win), Cmd+Shift+<strong>M</strong> (Mac)</li>
<li>Attempt completion: <strong>Tab</strong> or Ctrl+Space (Win), <strong>Tab</strong> or Cmd+Space (Mac),</li>
<li>Knit Document: Ctrl+Shift+<strong>K</strong> (Win), Cmd+Shift+<strong>K</strong> (Mac)</li>
<li>Copy Lines Up/Down: Shift+Alt+<strong><span class="math inline">\(\uparrow\)</span></strong>/<strong><span class="math inline">\(\downarrow\)</span></strong> (Win), Cmd+Option+<strong><span class="math inline">\(\uparrow\)</span></strong>/<strong><span class="math inline">\(\downarrow\)</span></strong> (Mac)</li>
</ul></li>
</ul>
</div>
<div id="new-assignment-github-workflow" class="section level3">
<h3>New Assignment Github Workflow</h3>
<div id="old" class="section level4">
<h4>OLD</h4>
<p>So far to turn in individual assignments, you’ve been editing <code>env-info/students/<user>.Rmd</code> and knitting to <code>env-info/students/<user>.html</code>. Then you push to your repo <code><user>/env-info</code> before submitting to the course repo <code>ucsb-bren/env-info</code> with a push, and pull request. To update your <code><user>/env-info</code> with the latest from <code>ucsb-bren/env-info</code>, you also need to do an additional pull request, merge, and pull.</p>
<table style="width:94%;">
<colgroup>
<col width="16%" />
<col width="19%" />
<col width="19%" />
<col width="19%" />
<col width="19%" />
</colgroup>
<thead>
<tr class="header">
<th align="left">repo location</th>
<th align="center"><code><user></code> permission</th>
<th align="center">initialize <i class="fa fa-arrow-down"></i></th>
<th align="center">edit <i class="fa fa-arrow-up"></i></th>
<th align="center">update <i class="fa fa-arrow-down"></i></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><i class="fa fa-cloud"></i> <code>github.com/ucsb-bren/env-info</code></td>
<td align="center">read only</td>
<td align="center"></td>
<td align="center"><a href="https://help.github.com/articles/merging-a-pull-request"><strong>merge</strong></a> <span class="octicon octicon-git-merge"></span> [BB]</td>
</tr>
<tr class="even">
<td align="left"><i class="fa fa-cloud"></i> <code>github.com/<user>/env-info</code></td>
<td align="center">read + write</td>
<td align="center"><a href="https://help.github.com/articles/fork-a-repo"><strong>fork</strong></a> <span class="octicon octicon-repo-forked"></span></td>
<td align="center"><a href="https://help.github.com/articles/creating-a-pull-request/"><strong>pull request</strong></a> <span class="octicon octicon-git-pull-request"></span></td>
<td align="center"><a href="https://help.github.com/articles/creating-a-pull-request/"><strong>pull request</strong></a> <span class="octicon octicon-git-pull-request"></span>, <a href="https://help.github.com/articles/merging-a-pull-request"><strong>merge</strong></a> <span class="octicon octicon-git-merge"></span></td>
</tr>
<tr class="odd">
<td align="left"><i class="fa fa-desktop"></i> <code>~/localdir/<user>.github.io</code></td>
<td align="center">read + write</td>
<td align="center"><a href="https://help.github.com/articles/fetching-a-remote"><strong>clone</strong></a> <span class="octicon octicon-desktop-download"></span></td>
<td align="center"><a href="http://git-scm.com/docs/git-commit"><strong>commit</strong></a> <span class="octicon octicon-git-commit"></span>, <a href="https://help.github.com/articles/pushing-to-a-remote/"><strong>push</strong></a> <span class="octicon octicon-cloud-upload"></span></td>
<td align="center"><a href="https://help.github.com/articles/fetching-a-remote/#pull"><strong>pull</strong></a> <span class="octicon octicon-cloud-download"></span></td>
</tr>
</tbody>
</table>
</div>
<div id="new" class="section level4">
<h4>NEW</h4>
<p>For future assignments, you’ll use a much simpler Github workflow with less possibilities for <a href="http://r-pkgs.had.co.nz/git.html#git-pull">merge conflicts</a>:</p>
<table style="width:94%;">
<colgroup>
<col width="16%" />
<col width="19%" />
<col width="19%" />
<col width="19%" />
<col width="19%" />
</colgroup>
<thead>
<tr class="header">
<th align="left">repo location</th>
<th align="center"><code><user></code> permission</th>
<th align="center">initialize <i class="fa fa-arrow-down"></i></th>
<th align="center">edit <i class="fa fa-arrow-up"></i></th>
<th align="center">update <i class="fa fa-arrow-down"></i></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><i class="fa fa-cloud"></i> <code>github.com/<user>/<user>.github.io</code></td>
<td align="center">read + write</td>
<td align="center"><a href="https://help.github.com/articles/create-a-repo/"><strong>create</strong></a> <span class="octicon octicon-plus"></span></td>
<td align="center"></td>
</tr>
<tr class="even">
<td align="left"><i class="fa fa-desktop"></i> <code>~/localdir/<user>.github.io</code></td>
<td align="center">read + write</td>
<td align="center"><a href="https://help.github.com/articles/fetching-a-remote"><strong>clone</strong></a> <span class="octicon octicon-desktop-download"></span></td>
<td align="center"><a href="http://git-scm.com/docs/git-commit"><strong>commit</strong></a> <span class="octicon octicon-git-commit"></span>, <a href="https://help.github.com/articles/pushing-to-a-remote/"><strong>push</strong></a> <span class="octicon octicon-cloud-upload"></span></td>
<td align="center"><a href="https://help.github.com/articles/fetching-a-remote/#pull"><strong>pull</strong></a> <span class="octicon octicon-cloud-download"></span></td>
</tr>
</tbody>
</table>
<p>Similar to your class group project repo <code><org>/<org>.github.io</code> which serves a web site at <code>http://<org>.github.io</code>, you want to initialize:</p>
<ol style="list-style-type: decimal">
<li><p><a href="https://help.github.com/articles/create-a-repo/">Create a repository</a> <code><user>/<user>.github.io</code> where you’ll replace <code><user></code> with your Github username (eg I created a repository <code>bbest.github.io</code> in which <code>bbest</code> is the owner). If you already have this repository created, you can simply move on. Otherwise, please also tick the box to initialize this repository with a README.</p></li>
<li><p>Go to <span class="octicon octicon-gear"></span> Settings, Collaborators and add <code>bbest</code> and <code>naomitague</code> as collaborators. This will give us write permissions on your repository, enabling us to more easily help you fix code.</p></li>
<li><p>Run the equivalent of <code>git clone http://github.com/<user>/<user>.github.io</code> from RStudio menu File, New Project…, Version Control, Git.</p></li>
<li><p>Create a new folder <code>env-info_hw</code> inside your local repository <code><user>.github.io</code>.</p></li>
</ol>
<p>It is important that you use the exact spelling for all of the above. Otherwise, we won’t be able to find your homework.</p>
</div>
</div>
<div id="individual-assignment-wk05_ggplot" class="section level3">
<h3>Individual Assignment <code>wk05_ggplot</code></h3>
<p>Now, for every week’s assignment you’ll create a new Rmarkdown file inside the <code>env-info_hw</code> folder of your <code><user>.github.io</code> repo. This week create one called <code>wk05_ggplot.Rmd</code> with File, New File…, R Markdown…</p>
<p>We’ll be able to grade assignments, because we have a roster of students by Github username, and so presume we’ll find your assignment by visiting <code>http://<user>.github.io/env-info_hw/wk05_ggplot.html</code>, eg <code>http://bbest.github.io/env-info_hw/wk05_ggplot.html</code>.</p>
<p>Again, it is important that you use the exact spelling above. Otherwise, we won’t be able to find your homework.</p>
</div>
</div>
<div id="joining-data" class="section level2">
<h2>joining data</h2>
<p>For this portion of the individual assignment, similar to last week, you’ll find it easiest to copy and paste from <code>## joining data</code> onwards in <a href="https://raw.githubusercontent.com/ucsb-bren/env-info/gh-pages/wk05_joining.Rmd"><code>env-info/wk05_joining.Rmd</code></a> to your <code><user>.github.io/env-info_hw/wk05_ggplot.Rmd</code>. Then you can play with different chunks of the code. Please be sure to answer all tasks and questions at the bottom.</p>
<p>The R chunks explaining the <code>dplyr</code> join functions below are pulled from the excellent <a href="wk03_dplyr/wrangling-webinar.pdf"><strong>wrangling-webinar.pdf</strong></a> presentation, which you should consult as you execute (see shortcuts in <a href="refs/cheatsheets/rstudio-IDE-cheatsheet.pdf">rstudio-IDE-cheatsheet.pdf</a>).</p>
<div id="setup" class="section level3">
<h3>setup</h3>
<p>Ensure that you’re in the same working directory <code>env-info_hw</code> when you Knit HTML as when you test code in the Console.</p>
<pre class="r"><code>wd = 'env-info_hw'
# set working directory for Console (vs Rmd)
if (wd %in% list.files() & interactive()){
setwd(wd)
}
# ensure working directory
if (basename(getwd()) != wd){
stop(sprintf("WHOAH! Your working directory is not in '%s'!\n getwd(): %s", wd, getwd()))
}</code></pre>
</div>
<div id="bind_cols" class="section level3">
<h3><code>bind_cols</code></h3>
<p>bind columns between data frames</p>
<pre class="r"><code>library(readr)
library(dplyr)
y = read_csv(
'x1,x2
A,1
B,2
C,3')
z = read_csv(
'x1,x2
B,2
C,3
D,4')
y
z
bind_cols(y, z)</code></pre>
</div>
<div id="bind_rows" class="section level3">
<h3><code>bind_rows</code></h3>
<p>bind rows of data frames</p>
<pre class="r"><code>y
z
bind_rows(y, z)</code></pre>
</div>
<div id="union" class="section level3">
<h3><code>union</code></h3>
<p>set operation on data frames, returning all unique rows</p>
<pre class="r"><code>y
z
union(y, z)</code></pre>
</div>
<div id="intersect" class="section level3">
<h3><code>intersect</code></h3>
<p>set operation on data frames, returning those rows in common</p>
<pre class="r"><code>y
z
intersect(y, z)</code></pre>
</div>
<div id="setdiff" class="section level3">
<h3><code>setdiff</code></h3>
<p>set operation on data frames, returning all mismatched rows</p>
<pre class="r"><code>y
z
setdiff(y, z)</code></pre>
</div>
<div id="left_join" class="section level3">
<h3><code>left_join</code></h3>
<p>return all rows from x, and all columns from x and y. Rows in x with no match in y will have NA values in the new columns.</p>
<pre class="r"><code>artists = read_csv(
'name,plays
George,sitar
John,guitar
Paul,bass
Ringo,drums')
songs = read_csv(
'song,name
Across the Universe,John
Come Together,John
"Hello, Goodbye",Paul
Peggy Sue,Buddy')
artists
songs
left_join(songs, artists, by='name')</code></pre>
</div>
<div id="inner_join" class="section level3">
<h3><code>inner_join</code></h3>
<p>return all rows from x where there are matching values in y, and all columns from x and y</p>
<pre class="r"><code>inner_join(songs, artists, by = "name")</code></pre>
</div>
<div id="semi_join" class="section level3">
<h3><code>semi_join</code></h3>
<p>return all rows from x where there are matching values in y, keeping just columns from x</p>
<pre class="r"><code>semi_join(songs, artists, by = "name")</code></pre>
</div>
<div id="anti_join" class="section level3">
<h3><code>anti_join</code></h3>
<p>return all rows from x where there are not matching values in y, keeping just columns from x</p>
<pre class="r"><code>anti_join(songs, artists, by = "name")</code></pre>
</div>
<div id="per-capita-co2-emissions" class="section level3">
<h3>per capita CO<sub>2</sub> emissions</h3>
<p>You’ll join the <a href="http://data.okfn.org/data/core/population">population</a> dataset to calculate per capita CO<sub>2</sub> emissions.</p>
<p><em><strong>Task</strong>. Calculate the per capita emissions by country (not World or EU28) and return the top 5 emitting countries for <strong>2014</strong>.</em></p>
<p><em><strong>Task</strong>. Summarize the per capita emissions by country (not World or EU28) as the <strong>mean</strong> (ie average) value across all years and return the top 5 emitting countries.</em></p>
<pre class="r"><code>suppressPackageStartupMessages({
library(readr)
library(readxl) # install.packages('readxl')
library(dplyr)
library(tidyr)
library(httr) # install.packages('httr')
})
# co2 Excel file
url = 'http://edgar.jrc.ec.europa.eu/news_docs/CO2_1970-2014_dataset_of_CO2_report_2015.xls'
xls = 'co2_europa.xls'
if (!file.exists(xls)) writeBin(content(GET(url), 'raw'), xls)
# read in carbon dioxide emissions file
co2 = read_excel(xls, skip=12) %>%
gather(year, ktons_co2, -Country) %>%
filter(!Country %in% c('World','EU28') & !is.na(Country)) %>%
mutate(year = as.integer(as.character(year))) %>%
rename(country=Country)</code></pre>
<pre><code>## DEFINEDNAME: 21 00 00 01 0b 00 00 00 01 00 00 00 00 00 00 0d 3b 00 00 0c 00 e0 00 00 00 2c 00
## DEFINEDNAME: 21 00 00 01 0b 00 00 00 01 00 00 00 00 00 00 0d 3b 00 00 0c 00 e0 00 00 00 2c 00
## DEFINEDNAME: 21 00 00 01 0b 00 00 00 01 00 00 00 00 00 00 0d 3b 00 00 0c 00 e0 00 00 00 2c 00
## DEFINEDNAME: 21 00 00 01 0b 00 00 00 01 00 00 00 00 00 00 0d 3b 00 00 0c 00 e0 00 00 00 2c 00</code></pre>
<pre class="r"><code>co2</code></pre>
<pre><code>## Source: local data frame [9,720 x 3]
##
## country year ktons_co2
## (chr) (int) (dbl)
## 1 Afghanistan 1970 1813.981234
## 2 Albania 1970 4435.433037
## 3 Algeria 1970 18850.745443
## 4 American Samoa 1970 6.183023
## 5 Angola 1970 8946.495011
## 6 Anguilla 1970 2.168006
## 7 Antigua and Barbuda 1970 196.161773
## 8 Argentina 1970 87478.401090
## 9 Armenia 1970 10951.012839
## 10 Aruba 1970 40.380782
## .. ... ... ...</code></pre>
<pre class="r"><code># read in population
popn = read_csv('https://raw.githubusercontent.com/datasets/population/master/data/population.csv') %>%
select(country=`Country Name`, year=Year, popn=Value)
popn</code></pre>
<pre><code>## Source: local data frame [13,484 x 3]
##
## country year popn
## (chr) (int) (dbl)
## 1 Arab World 1960 93485943
## 2 Arab World 1961 96058179
## 3 Arab World 1962 98728995
## 4 Arab World 1963 101496308
## 5 Arab World 1964 104359772
## 6 Arab World 1965 107318159
## 7 Arab World 1966 110379639
## 8 Arab World 1967 113543760
## 9 Arab World 1968 116787194
## 10 Arab World 1969 120078092
## .. ... ... ...</code></pre>
<p>In order to calculate per capita emissions, you’ll need to join the <code>popn</code> data frame with the <code>co2</code> data frame before calculating something like <code>ktons_co2 / popn</code>.</p>
<p>One of the trickiest parts about joining data is ensuring that values in the key columns are matching. The column <code>year</code> is a simple 4 digit integer in both tables (after converting to <code>as.integer()</code> for the gathered <code>co2</code>). But what about <code>country</code>?</p>
<p>Let’s look at just <code>year==2014</code> to see what values of <code>country</code> in table <code>co2</code> are not found in table <code>popn</code>, ie <code>anti_join()</code>:</p>
<pre class="r"><code># co2$popn not in popn$country
co2 %>%
filter(year==2014) %>%
anti_join(
popn %>%
filter(year==2014),
by='country') %>%
arrange(desc(ktons_co2))</code></pre>
<pre><code>## Source: local data frame [47 x 3]
##
## country year ktons_co2
## (chr) (int) (dbl)
## 1 United States of America 2014 5334529.74
## 2 Int. Shipping 2014 624493.37
## 3 Iran (Islamic Republic of) 2014 618197.22
## 4 Republic of Korea 2014 610065.60
## 5 Int. Aviation 2014 492174.61
## 6 China, Taiwan Province of 2014 276674.74
## 7 Egypt 2014 225111.50
## 8 Venezuela (Bolivarian Republic of) 2014 195212.97
## 9 Viet Nam 2014 190221.79
## 10 Democratic People s Republic of Korea 2014 59858.59
## .. ... ... ...</code></pre>
<p>Whoah, we’re missing 47 “countries”, including the “United States of America”! So what is “United States of America” called in <code>popn$country</code>?</p>
<pre class="r"><code># popn$country not in co2$popn
popn %>%
filter(year==2014) %>%
anti_join(
co2 %>%
filter(year==2014),
by='country') %>%
arrange(desc(country))</code></pre>
<pre><code>## Source: local data frame [78 x 3]
##
## country year popn
## (chr) (int) (dbl)
## 1 Yemen, Rep. 2014 24968508
## 2 World 2014 7207735030
## 3 West Bank and Gaza 2014 4294682
## 4 Virgin Islands (U.S.) 2014 104170
## 5 Vietnam 2014 90730000
## 6 Venezuela, RB 2014 30851343
## 7 Upper middle income 2014 2354905613
## 8 United States 2014 318857056
## 9 Tanzania 2014 50757459
## 10 Sudan 2014 38764090
## .. ... ... ...</code></pre>
<p>Ok, so in <code>popn$country</code> we have “United States” which doesn’t get matched with “United States of America” in <code>co2$country</code>? How to fix this? We need a lookup table for translating country values between tables. I went ahead and made one for you by copying the two anti_join tables above and matching rows where possible.</p>
<pre class="r"><code># get lookup table to translate popn$country to co2$country
cntry = read_csv('https://raw.githubusercontent.com/ucsb-bren/env-info/gh-pages/data/co2_country_to_popn.csv')
cntry</code></pre>
<pre><code>## Source: local data frame [28 x 2]
##
## country_co2 country_popn
## (chr) (chr)
## 1 Bahamas Bahamas, The
## 2 Bolivia (Plurinational State of) Bolivia
## 3 Democratic Republic of the Congo Congo, Dem. Rep.
## 4 Congo Congo, Rep.
## 5 C\x99te d Ivoire Cote d'Ivoire
## 6 Egypt Egypt, Arab Rep.
## 7 Faroe Islands Faeroe Islands
## 8 Gambia Gambia, The
## 9 China, Hong Kong SAR Hong Kong SAR, China
## 10 Iran (Islamic Republic of) Iran, Islamic Rep.
## .. ... ...</code></pre>
<p>So before we join the tables <code>co2</code> and <code>popn</code>, first translate country in one to match the other.</p>
<pre class="r"><code># update co2$country to popn$country
co2_m = co2 %>%
left_join(
cntry,
# note use of named vector to columns with different names
by = c('country'='country_co2')) %>%
mutate(
# note use of ifelse to upated country with popn$country_popn
country = ifelse(!is.na(country_popn), country_popn, country))
# check that "United States of America" changed to "United States"
co2_m %>%
filter(year==2014) %>%
arrange(desc(country)) %>%
head(15)</code></pre>
<pre><code>## Source: local data frame [15 x 4]
##
## country year ktons_co2 country_popn
## (chr) (int) (dbl) (chr)
## 1 Zimbabwe 2014 1.313540e+04 NA
## 2 Zambia 2014 3.367057e+03 NA
## 3 Yemen, Rep. 2014 2.255319e+04 Yemen, Rep.
## 4 Western Sahara 2014 2.074151e+02 NA
## 5 Virgin Islands (U.S.) 2014 1.489644e+00 Virgin Islands (U.S.)
## 6 Vietnam 2014 1.902218e+05 Vietnam
## 7 Venezuela, RB 2014 1.952130e+05 Venezuela, RB
## 8 Vanuatu 2014 1.105213e+02 NA
## 9 Uzbekistan 2014 1.226212e+05 NA
## 10 Uruguay 2014 8.113994e+03 NA
## 11 United States 2014 5.334530e+06 United States
## 12 United Kingdom 2014 4.154209e+05 NA
## 13 United Arab Emirates 2014 2.010522e+05 NA
## 14 Ukraine 2014 2.490653e+05 NA
## 15 Uganda 2014 4.891807e+03 NA</code></pre>
<p>Ok, so <code>co2_m$country</code> got updated with values to match <code>popn$country</code>, eg “United States of America” to “United States”.</p>
<p>Please use this matching <code>co2_m</code> to join with <code>popn</code> and calculate per capita emissions.</p>
</div>
</div>
</div> <!--span-9-->
</div> <!--row-fluid-->
<!--
<script src="{{ site.baseurl }}/libs/lightbox-2.8.2/js/lightbox.min.js"></script>
<script>
lightbox.option({
'albumLabel': 'Example %1 of %2',
'resizeDuration': 200,
'fadeDuration': 200,
'wrapAround': true
})
</script>
-->
<style type="text/css">
.main-container {
max-width: none;
}
</style>
<script>
$(function() {
var toc = $("#toc").tocify({
selectors: "h2,h3",
theme: "bootstrap3",
context: '.main-content',
hashGenerator: 'pretty',
showAndHide: false
}).data("toc-tocify");
$(".optionName").popover({ trigger: "hover" });
});
</script>
<div style="color:gray; text-align: right;" >
<span class="octicon octicon-repo-forked"></span> <b>Fork</b> me at <a href="http://github.com/ucsb-bren/env-info">github.com/<b>ucsb-bren/env-info</b></a>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
$(document).ready(function () {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>