forked from kbroman/datacarpentry_R_2017-01-10
-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-notes.html
320 lines (274 loc) · 14.8 KB
/
02-notes.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
<!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="Data Carpentry contributors" />
<title>Aggregating and analyzing data with dplyr (notes)</title>
<script src="libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="libs/navigation-1.1/tabsets.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; background-color: #f8f8f8; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
pre, code { background-color: #f8f8f8; }
code > span.kw { color: #204a87; font-weight: bold; }
code > span.dt { color: #204a87; }
code > span.dv { color: #0000cf; }
code > span.bn { color: #0000cf; }
code > span.fl { color: #0000cf; }
code > span.ch { color: #4e9a06; }
code > span.st { color: #4e9a06; }
code > span.co { color: #8f5902; font-style: italic; }
code > span.ot { color: #8f5902; }
code > span.al { color: #ef2929; }
code > span.fu { color: #000000; }
code > span.er { font-weight: bold; }
</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<style type="text/css">
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;
}
.table th:not([align]) {
text-align: left;
}
</style>
</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;
}
.tabbed-pane {
padding-top: 12px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Aggregating and analyzing data with dplyr (notes)</h1>
<h4 class="author"><em>Data Carpentry contributors</em></h4>
</div>
<div id="TOC">
<ul>
<li><a href="#key-idea">Key idea</a></li>
<li><a href="#install-and-load-the-library">Install and load the library</a></li>
<li><a href="#select-and-filter">Select and filter</a></li>
<li><a href="#pipe">Pipe</a><ul>
<li><a href="#challenge">Challenge</a></li>
</ul></li>
<li><a href="#mutate">Mutate</a><ul>
<li><a href="#challenge-1">Challenge</a></li>
<li><a href="#split-apply-combine-data-analyses-group-by-and-summarize">split-apply-combine data analyses (group-by and summarize)</a></li>
<li><a href="#challenge-2">Challenge</a></li>
<li><a href="#challenge-3">Challenge</a></li>
<li><a href="#challenge-4">Challenge</a></li>
</ul></li>
<li><a href="#data-cleaning-preparations">Data cleaning preparations</a></li>
</ul>
</div>
<div id="key-idea" class="section level2">
<h2>Key idea</h2>
<p>All that bracket-based selecting can be a bit cumbersome. Add-on package dplyr greatly simplifies the process; inspired by SQL.</p>
<p><code>select</code>, <code>filter</code>, <code>mutate</code>, <code>group_by</code>, <code>summarize</code></p>
<p>(also <code>tally</code> and <code>arrange</code>)</p>
</div>
<div id="install-and-load-the-library" class="section level2">
<h2>Install and load the library</h2>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">install.packages</span>(<span class="st">"dplyr"</span>)
<span class="kw">install.packages</span>(<span class="st">"ggplot2"</span>)</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(dplyr)</code></pre>
</div>
<div id="select-and-filter" class="section level2">
<h2>Select and filter</h2>
<p>Select to grab columns.</p>
<pre class="sourceCode r"><code class="sourceCode r">selectedcol <-<span class="st"> </span><span class="kw">select</span>(surveys, species_id, plot_type, weight)
<span class="kw">head</span>(selectedcol)</code></pre>
<p>Filter to grab rows.</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys2002 <-<span class="st"> </span><span class="kw">filter</span>(surveys, year==<span class="dv">2002</span>)
<span class="kw">head</span>(surveys2002)</code></pre>
</div>
<div id="pipe" class="section level2">
<h2>Pipe</h2>
<p>Output of one function becomes the input to the next.</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">filter</span>(weight <<span class="st"> </span><span class="dv">5</span>) %>%
<span class="st"> </span><span class="kw">select</span>(species_id, sex, weight)</code></pre>
<p><kbd><code>Ctrl</code></kbd> + <kbd><code>Shift</code></kbd> + <kbd><code>M</code></kbd> to insert <code>%>%</code></p>
<p>Could assign this to something:</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys_sml <-<span class="st"> </span>surveys %>%
<span class="st"> </span><span class="kw">filter</span>(weight <<span class="st"> </span><span class="dv">5</span>) %>%
<span class="st"> </span><span class="kw">select</span>(species_id, sex, weight)</code></pre>
<div id="challenge" class="section level3">
<h3>Challenge</h3>
<p>Using pipes, subset the data to include individuals collected before 1995, and retain the columns <code>year</code>, <code>sex</code>, and <code>weight.</code></p>
</div>
</div>
<div id="mutate" class="section level2">
<h2>Mutate</h2>
<p><code>mutate()</code> to derive a new column.</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">mutate</span>(<span class="dt">weight_kg =</span> weight /<span class="st"> </span><span class="dv">1000</span>)</code></pre>
<p>To just look at the top:</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">mutate</span>(<span class="dt">weight_kg =</span> weight /<span class="st"> </span><span class="dv">1000</span>) %>%
<span class="st"> </span>head</code></pre>
<p>Filter out <code>NA</code>s:</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">filter</span>(!<span class="kw">is.na</span>(weight)) %>%
<span class="st"> </span><span class="kw">mutate</span>(<span class="dt">weight_kg =</span> weight /<span class="st"> </span><span class="dv">1000</span>) %>%
<span class="st"> </span>head</code></pre>
<div id="challenge-1" class="section level3">
<h3>Challenge</h3>
<p>Create a new dataframe from the survey data that meets the following criteria: contains only the <code>species_id</code> column and a column that contains values that are the square-root of <code>hindfoot_length</code> values (e.g. a new column <code>hindfoot_sqrt</code>). In this <code>hindfoot_sqrt</code> column, there are no NA values and all values are < 3.</p>
<p>Hint: think about how the commands should be ordered</p>
</div>
<div id="split-apply-combine-data-analyses-group-by-and-summarize" class="section level3">
<h3>split-apply-combine data analyses (group-by and summarize)</h3>
<p>Many analyses fit a split-apply-combine pattern: split the data into groups, apply some analysis to each group, and then combine the results.</p>
<p>With dplyr, we use <code>group_by()</code> for the splitting and <code>tally</code> or <code>summarize()</code> for the rest.</p>
<p>Count individuals by sex:</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">group_by</span>(sex) %>%
<span class="st"> </span><span class="kw">tally</span>()</code></pre>
<p>Average weight by sex:</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">group_by</span>(sex) %>%
<span class="st"> </span><span class="kw">summarize</span>(<span class="dt">mean_weight =</span> <span class="kw">mean</span>(weight, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>))</code></pre>
<p>Can group by multiple columns:</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">group_by</span>(sex, species_id) %>%
<span class="st"> </span><span class="kw">summarize</span>(<span class="dt">mean_weight =</span> <span class="kw">mean</span>(weight, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>))</code></pre>
<p>Maybe filter those <code>NA</code>s</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">group_by</span>(sex, species_id) %>%
<span class="st"> </span><span class="kw">summarize</span>(<span class="dt">mean_weight =</span> <span class="kw">mean</span>(weight, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)) %>%
<span class="st"> </span><span class="kw">filter</span>(!<span class="kw">is.na</span>(mean_weight))</code></pre>
<p>Another thing we might do here is sort rows by <code>mean_weight</code>, using <code>arrange()</code>.</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">group_by</span>(sex, species_id) %>%
<span class="st"> </span><span class="kw">summarize</span>(<span class="dt">mean_weight =</span> <span class="kw">mean</span>(weight, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)) %>%
<span class="st"> </span><span class="kw">filter</span>(!<span class="kw">is.na</span>(mean_weight)) %>%
<span class="st"> </span><span class="kw">arrange</span>(mean_weight)</code></pre>
<p>If you want them sorted from highest to lowest, use <code>desc()</code>.</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">group_by</span>(sex, species_id) %>%
<span class="st"> </span><span class="kw">summarize</span>(<span class="dt">mean_weight =</span> <span class="kw">mean</span>(weight, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)) %>%
<span class="st"> </span><span class="kw">filter</span>(!<span class="kw">is.na</span>(mean_weight)) %>%
<span class="st"> </span><span class="kw">arrange</span>(<span class="kw">desc</span>(mean_weight))</code></pre>
<p>Also note that you can include multiple summaries.</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys %>%
<span class="st"> </span><span class="kw">group_by</span>(sex, species_id) %>%
<span class="st"> </span><span class="kw">summarize</span>(<span class="dt">mean_weight =</span> <span class="kw">mean</span>(weight, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>),
<span class="dt">min_weight =</span> <span class="kw">min</span>(weight, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)) %>%
<span class="st"> </span><span class="kw">filter</span>(!<span class="kw">is.na</span>(mean_weight)) %>%
<span class="st"> </span><span class="kw">arrange</span>(<span class="kw">desc</span>(mean_weight))</code></pre>
</div>
<div id="challenge-2" class="section level3">
<h3>Challenge</h3>
<p>How many times was each <code>plot_type</code> surveyed?</p>
</div>
<div id="challenge-3" class="section level3">
<h3>Challenge</h3>
<p>Use <code>group_by()</code> and <code>summarize()</code> to find the mean, min, and max hindfoot length for each species.</p>
</div>
<div id="challenge-4" class="section level3">
<h3>Challenge</h3>
<p>What was the heaviest animal measured in each year? Return the columns <code>year</code>, <code>genus</code>, <code>species</code>, and <code>weight</code>.</p>
</div>
</div>
<div id="data-cleaning-preparations" class="section level2">
<h2>Data cleaning preparations</h2>
<p>In preparations for the plotting, let’s do a bit of data cleaning: remove rows with missing <code>species_id</code>, <code>weight</code>, <code>hindfoot_length</code>, or <code>sex</code>.</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys_complete <-<span class="st"> </span>surveys %>%
<span class="st"> </span><span class="kw">filter</span>(species_id !=<span class="st"> ""</span>, !<span class="kw">is.na</span>(weight)) %>%
<span class="st"> </span><span class="kw">filter</span>(!<span class="kw">is.na</span>(hindfoot_length), sex !=<span class="st"> ""</span>)</code></pre>
<p>There are a lot of species with low counts. Let’s remove the species with less than 10 counts.</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># count records per species</span>
species_counts <-<span class="st"> </span>surveys_complete %>%
<span class="st"> </span><span class="kw">group_by</span>(species_id) %>%
<span class="st"> </span>tally
<span class="kw">head</span>(species_counts)
<span class="co"># get names of the species with counts >= 10</span>
frequent_species <-<span class="st"> </span>species_counts %>%
<span class="st"> </span><span class="kw">filter</span>(n >=<span class="st"> </span><span class="dv">10</span>) %>%
<span class="st"> </span><span class="kw">select</span>(species_id)
<span class="co"># filter out the less-frequent species</span>
surveys_complete <-<span class="st"> </span>surveys_complete %>%
<span class="st"> </span><span class="kw">filter</span>(species_id %in%<span class="st"> </span>frequent_species$species_id)</code></pre>
<p>We might save this to a file:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">write.csv</span>(reduced, <span class="st">"CleanData/portal_data_reduced.csv"</span>)</code></pre>
<p><br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/></p>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</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>