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
/
wk04_tidyr.html
477 lines (429 loc) · 20.4 KB
/
wk04_tidyr.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
<!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" />
<title>Week 4: Tidying up Data</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">Week 4: Tidying up Data</h1>
<h4 class="author"><em>Ben Best</em></h4>
<h4 class="date"><em>2016-02-09 14:34</em></h4>
</div>
<div id="precursors" class="section level2">
<h2>Precursors</h2>
<div id="final-project" class="section level3">
<h3>Final Project</h3>
<p>The instructions for your class group’s <a href="./#final-project">Final Project</a> have been updated.</p>
</div>
<div id="schedule" class="section level3">
<h3>Schedule</h3>
<p>The class for week 9 on March 4th conflicts with the <a href="http://www.bren.ucsb.edu/research/gp_submit.html">Bren Group Project</a> presentations, so we’ll be extending the classes before and after by 1 hour.</p>
</div>
<div id="invitations" class="section level3">
<h3>Invitations</h3>
<ul>
<li><p><strong>organizations</strong>: invite <span class="citation">@bbest</span> and <span class="citation">@naomitague</span> to your <code>github.com/<org></code> so we can directly <em>push</em> to your site (vs <em>fork</em> & <em>pull request</em>)</p></li>
<li><p><strong>auditors</strong>: email <a href="mailto:[email protected]">[email protected]</a> to ensure you get announcements via GauchoSpace</p></li>
</ul>
</div>
<div id="setwd" class="section level3">
<h3><code>setwd()</code></h3>
<p>As mentioned in <a href="./wk03_dplyr.html#where-am-i?-getting-around-in-the-command-line">wk03_dplyr</a>, the working directory when knitting your Rmarkdown file is always the folder in which it is contained, eg for <code>env-info/students/bbest.Rmd</code> the working directory is <code>env-info/students</code>. This may be different from your R Console in RStudio which defaults to the working directory to the top level folder of your project, ie <code>env-info</code>. To get the two to be the same as you test code in the Console before knitting the Rmarkdown to HTML, I <strong>REQUIRE</strong> you to insert the following R chunk near the beginning (but after the Rmarkdown front matter surrounded by the rows <code>---</code>) of your <code>env-info/students/<user>.Rmd</code>:</p>
<pre class="r"><code># set working directory if has students directory and at R Console (vs knitting)
if ('students' %in% list.files() & interactive()){
setwd('students' )
}
# ensure working directory is students
if (basename(getwd()) != 'students'){
stop(sprintf("WHOAH! Your working directory is not in 'students'!\n getwd(): %s", getwd()))
}</code></pre>
<p>This then ensures that “relative” paths will work the same in your R Console as when knitting your Rmarkdown to HTML. For instance:</p>
<pre class="r"><code># absolute: /Users/bbest/github/env-info/students/data/bbest_ports-bc.csv
d = read.csv('./data/bbest_ports-bc.csv') # ./data is child of students
# absolute: /Users/bbest/github/env-info/data/r-ecology/surveys.csv
d = read.csv('../data/r-ecology/surveys.csv') # ../data is sibling of students</code></pre>
<p>The first path uses this folder <code>.</code> since that <code>data</code> folder is a “child” of the <code>students</code> folder, whereas the second path backs up a folder <code>..</code> before descending into the other <code>data</code> folder that is a “sibling” of the <code>students</code> folder.</p>
</div>
<div id="assignment-individual" class="section level3">
<h3>Assignment (Individual)</h3>
<p>For the data wrangling portion of today, append the header <code>## 4. Tidying up Data</code> to your <code>env-info/students/<user>.Rmd</code> and include R chunks to run the demo below and give yourself the opportunity to try out possibilities with the code. Please set aside another header below this section <code>## 4. Answers and Tasks</code> where you answer questions and perform tasks on applying the functions to the CO<sub>2</sub> dataset as R chunks. Please include the question or task above the R chunk or answer.</p>
<p>You’ll find it easiest to copy and paste the demo portion from <a href="https://raw.githubusercontent.com/ucsb-bren/env-info/gh-pages/wk04_tidyr.Rmd"><code>env-info/wk04_tidyr.Rmd</code></a> but will need to understand this material enough to apply to the questions and tasks.</p>
<p>You will want to synchronize with <code>ucsb-bren/env-info</code> (ie <em>pull request</em> <code>ucsb-bren/env-info</code> to <code><user>/env-info</code>, <em>merge</em> the pull request in <code><user>/env-info</code>, and <em>pull</em> to update your local machine), in order to successfully knit your <code>env-info/students/<user>.Rmd</code>. The Rmarkdown below expects <code>env-info/wk04_tidyr/img/data-wrangling-cheatsheet_tidyr.png</code> and <code>env-info/data/co2_europa.xls</code> which are in the updated <code>ucsb-bren/env-info</code>.</p>
</div>
</div>
<div id="data" class="section level2">
<h2>data</h2>
<p>The R chunks explaining the <code>dplyr</code> and <code>tidyr</code> 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="edawr" class="section level3">
<h3>EDAWR</h3>
<pre class="r"><code># install.packages("devtools")
# devtools::install_github("rstudio/EDAWR")
library(EDAWR)
help(package='EDAWR')
?storms # wind speed data for 6 hurricanes
?cases # subset of WHO tuberculosis
?pollution # pollution data from WHO Ambient Air Pollution, 2014
?tb # tuberculosis data
View(storms)
View(cases)
View(pollution)</code></pre>
</div>
<div id="slicing" class="section level3">
<h3>slicing</h3>
<pre class="r"><code># storms
storms$storm
storms$wind
storms$pressure
storms$date
# cases
cases$country
names(cases)[-1]
unlist(cases[1:3, 2:4])
# pollution
pollution$city[c(1,3,5)]
pollution$amount[c(1,3,5)]
pollution$amount[c(2,4,6)]
# ratio
storms$pressure / storms$wind</code></pre>
<pre class="r"><code># better yet
library(dplyr)
pollution %>%
filter(city != 'New York') %>%
mutate(
ratio = pressure / wind)</code></pre>
</div>
</div>
<div id="tidyr" class="section level2">
<h2>tidyr</h2>
<p>Two main functions: gather() and spread()</p>
<pre class="r"><code># install.packages("tidyr")
library(tidyr)
?gather # gather to long
?spread # spread to wide</code></pre>
<div id="gather" class="section level3">
<h3><code>gather</code></h3>
<pre class="r"><code>cases
gather(cases, "year", "n", 2:4)
gather(cases, "year", "n", -1)</code></pre>
</div>
<div id="spread" class="section level3">
<h3><code>spread</code></h3>
<pre class="r"><code>pollution
spread(pollution, size, amount)</code></pre>
<p>Other functions to extract and combine columns…</p>
</div>
<div id="separate" class="section level3">
<h3><code>separate</code></h3>
<pre class="r"><code>storms
storms2 = separate(storms, date, c("year", "month", "day"), sep = "-")</code></pre>
</div>
<div id="unite" class="section level3">
<h3><code>unite</code></h3>
<pre class="r"><code>storms2
unite(storms2, "date", year, month, day, sep = "-")</code></pre>
<p><strong>Recap: tidyr</strong>:</p>
<ul>
<li><p>A package that reshapes the layout of data sets.</p></li>
<li><p>Make observations from variables with <code>gather()</code> Make variables from observations with <code>spread()</code></p></li>
<li><p>Split and merge columns with <code>unite()</code> and <code>separate()</code></p></li>
</ul>
<p>From the <a href="./refs/cheatsheets/data-wrangling-cheatsheet.pdf">data-wrangling-cheatsheet.pdf</a>:</p>
<div class="figure">
<img src="wk04_tidyr/img/data-wrangling-cheatsheet_tidyr.png" alt="" />
</div>
</div>
<div id="tidy-co2-emissions" class="section level3">
<h3>tidy CO<sub>2</sub> emissions</h3>
<p><em><strong>Task</strong>. Convert the following table <a href="http://edgar.jrc.ec.europa.eu/overview.php?v=CO2ts1990-2014&sort=des9">CO<sub>2</sub> emissions per country since 1970</a> from wide to long format and output the first few rows into your Rmarkdown. I recommend consulting <code>?gather</code> and you should have 3 columns in your output.</em></p>
<pre class="r"><code>library(dplyr)
library(readxl) # install.packages('readxl')
# xls downloaded from http://edgar.jrc.ec.europa.eu/news_docs/CO2_1970-2014_dataset_of_CO2_report_2015.xls
xls = '../data/co2_europa.xls'
print(getwd())
co2 = read_excel(xls, skip=12)
co2</code></pre>
<p><em><strong>Question</strong>. Why use <code>skip=12</code> argument in <code>read_excel()</code>?</em></p>
</div>
</div>
<div id="dplyr" class="section level2">
<h2>dplyr</h2>
<p>A package that helps transform tabular data</p>
<pre class="r"><code># install.packages("dplyr")
library(dplyr)
?select
?filter
?arrange
?mutate
?group_by
?summarise</code></pre>
<p>See sections in the <a href="./refs/cheatsheets/data-wrangling-cheatsheet.pdf">data-wrangling-cheatsheet.pdf</a>:</p>
<ul>
<li>Subset Variables (Columns), eg <code>select()</code></li>
<li>Subset Observations (Rows), eg <code>filter()</code></li>
<li>Reshaping Data - Change the layout of a data set, eg <code>arrange()</code></li>
<li>Make New Variables, eg <code>mutate()</code></li>
<li>Group Data, eg <code>group_by()</code> and <code>summarise()</code></li>
</ul>
<div id="select" class="section level3">
<h3><code>select</code></h3>
<pre class="r"><code>storms
select(storms, storm, pressure)
storms %>% select(storm, pressure)</code></pre>
</div>
<div id="filter" class="section level3">
<h3><code>filter</code></h3>
<pre class="r"><code>storms
filter(storms, wind >= 50)
storms %>% filter(wind >= 50)
storms %>%
filter(wind >= 50) %>%
select(storm, pressure)</code></pre>
</div>
<div id="mutate" class="section level3">
<h3><code>mutate</code></h3>
<pre class="r"><code>storms %>%
mutate(ratio = pressure / wind) %>%
select(storm, ratio)</code></pre>
</div>
<div id="group_by" class="section level3">
<h3><code>group_by</code></h3>
<pre class="r"><code>pollution
pollution %>% group_by(city)</code></pre>
</div>
<div id="summarise" class="section level3">
<h3><code>summarise</code></h3>
<pre class="r"><code># by city
pollution %>%
group_by(city) %>%
summarise(
mean = mean(amount),
sum = sum(amount),
n = n())
# by size
pollution %>%
group_by(size) %>%
summarise(
mean = mean(amount),
sum = sum(amount),
n = n())</code></pre>
<p>note that <code>summarize</code> synonymously works</p>
</div>
<div id="ungroup" class="section level3">
<h3><code>ungroup</code></h3>
<pre class="r"><code>pollution %>%
group_by(size)
pollution %>%
group_by(size) %>%
ungroup()</code></pre>
</div>
<div id="multiple-groups" class="section level3">
<h3>multiple groups</h3>
<pre class="r"><code>tb %>%
group_by(country, year) %>%
summarise(cases = sum(cases))
summarise(cases = sum(cases))</code></pre>
<p><strong>Recap: dplyr</strong>:</p>
<ul>
<li><p>Extract columns with <code>select()</code> and rows with <code>filter()</code></p></li>
<li><p>Sort rows by column with <code>arrange()</code></p></li>
<li><p>Make new columns with <code>mutate()</code></p></li>
<li><p>Group rows by column with <code>group_by()</code> and <code>summarise()</code></p></li>
</ul>
<p>See sections in the <a href="./refs/cheatsheets/data-wrangling-cheatsheet.pdf">data-wrangling-cheatsheet.pdf</a>:</p>
<ul>
<li><p>Subset Variables (Columns), eg <code>select()</code></p></li>
<li><p>Subset Observations (Rows), eg <code>filter()</code></p></li>
<li><p>Reshaping Data - Change the layout of a data set, eg <code>arrange()</code></p></li>
<li><p>Make New Variables, eg <code>mutate()</code></p></li>
<li><p>Group Data, eg <code>group_by()</code> and <code>summarise()</code></p></li>
</ul>
</div>
<div id="summarize-co2-emissions" class="section level3">
<h3>summarize CO<sub>2</sub> emissions</h3>
<p><em><strong>Task</strong>. Report the top 5 emitting countries (not World or EU28) for <strong>2014</strong> using your long format table. (You may need to convert your year column from factor to numeric, eg <code>mutate(year = as.numeric(as.character(year)))</code>. As with most analyses, there are multiple ways to do this. I used the following additional functions: <code>filter</code>, <code>arrange</code>, <code>desc</code>, <code>head</code>)</em>.</p>
<p><em><strong>Task</strong>. Summarize the <strong>total</strong> emissions by country (not World or EU28) across years from your long format table and return the top 5 emitting countries. (As with most analyses, there are multiple ways to do this. I used the following functions: <code>filter</code>, <code>group_by</code>, <code>summarize</code>, <code>sum</code>, <code>arrange</code>, <code>desc</code>, <code>head</code>)</em>.</p>
</div>
</div>
<div id="joining-data" class="section level2">
<h2>joining data</h2>
<p>Next week, we’ll do a bit on joining data.</p>
</div>
<div id="references" class="section level2">
<h2>References</h2>
<div id="data-wrangling-in-r" class="section level3">
<h3>Data Wrangling in R</h3>
<ul>
<li><a href="%7B%7B%20site.baseurl%20%7D%7D/refs/cheatsheets/data-wrangling-cheatsheet.pdf">Data Wrangling (dplyr, tidyr) cheat sheet</a></li>
<li><a href="wrangling-webinar.pdf" class="uri">wrangling-webinar.pdf</a></li>
</ul>
</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>