-
Notifications
You must be signed in to change notification settings - Fork 3
/
02-dplyr.html
348 lines (304 loc) · 21.2 KB
/
02-dplyr.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
<!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</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>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
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; } /* Keyword */
code > span.dt { color: #204a87; } /* DataType */
code > span.dv { color: #0000cf; } /* DecVal */
code > span.bn { color: #0000cf; } /* BaseN */
code > span.fl { color: #0000cf; } /* Float */
code > span.ch { color: #4e9a06; } /* Char */
code > span.st { color: #4e9a06; } /* String */
code > span.co { color: #8f5902; font-style: italic; } /* Comment */
code > span.ot { color: #8f5902; } /* Other */
code > span.al { color: #ef2929; } /* Alert */
code > span.fu { color: #000000; } /* Function */
code > span.er { color: #a40000; font-weight: bold; } /* Error */
code > span.wa { color: #8f5902; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #000000; } /* Constant */
code > span.sc { color: #000000; } /* SpecialChar */
code > span.vs { color: #4e9a06; } /* VerbatimString */
code > span.ss { color: #4e9a06; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #000000; } /* Variable */
code > span.cf { color: #204a87; font-weight: bold; } /* ControlFlow */
code > span.op { color: #ce5c00; font-weight: bold; } /* Operator */
code > span.pp { color: #8f5902; font-style: italic; } /* Preprocessor */
code > span.ex { } /* Extension */
code > span.at { color: #c4a000; } /* Attribute */
code > span.do { color: #8f5902; font-weight: bold; font-style: italic; } /* Documentation */
code > span.an { color: #8f5902; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #8f5902; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #8f5902; font-weight: bold; font-style: italic; } /* Information */
</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 src="libs/navigation-1.1/tabsets.js"></script>
<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</h1>
<h4 class="author"><em>Data Carpentry contributors</em></h4>
</div>
<div id="TOC">
<ul>
<li><a href="#data-manipulation-using-dplyr">Data Manipulation using dplyr</a><ul>
<li><a href="#what-is-dplyr">What is <code>dplyr</code>?</a><ul>
<li><a href="#selecting-columns-and-filtering-rows">Selecting columns and filtering rows</a></li>
<li><a href="#pipes">Pipes</a></li>
<li><a href="#challenge">Challenge</a></li>
<li><a href="#mutate">Mutate</a></li>
<li><a href="#challenge-1">Challenge</a></li>
<li><a href="#split-apply-combine-data-analysis-and-the-summarize-function">Split-apply-combine data analysis and the summarize() function</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>
<li><a href="#a-bit-of-data-cleaning">A bit of data cleaning</a></li>
</ul></li>
</ul></li>
</ul>
</div>
<hr />
<div id="data-manipulation-using-dplyr" class="section level1">
<h1>Data Manipulation using dplyr</h1>
<p>Bracket subsetting is handy, but it can be cumbersome and difficult to read, especially for complicated operations. Enter <code>dplyr</code>. <code>dplyr</code> is a package for making data manipulation easier.</p>
<p>Packages in R are basically sets of additional functions that let you do more stuff. The functions we’ve been using so far, like <code>str()</code> or <code>data.frame()</code>, come built into R; packages give you access to more of them. Before you use a package for the first time you need to install it on your machine, and then you should to import it in every subsequent R session when you’ll need it.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">install.packages</span>(<span class="st">"dplyr"</span>)</code></pre></div>
<p>While we’re installing stuff, let’s also install the ggplot2 package, which we’ll use next.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">install.packages</span>(<span class="st">"ggplot2"</span>)</code></pre></div>
<p>You might get asked to choose a CRAN mirror – this is basically asking you to choose a site to download the package from. The choice doesn’t matter too much; we recommend the RStudio mirror.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(dplyr) ## load the package</code></pre></div>
<div id="what-is-dplyr" class="section level2">
<h2>What is <code>dplyr</code>?</h2>
<p>The package <code>dplyr</code> provides easy tools for the most common data manipulation tasks. It is built to work directly with data frames. The thinking behind it was largely inspired by the package <code>plyr</code> which has been in use for some time but suffered from being slow in some cases.<code>dplyr</code> addresses this by porting much of the computation to C++. An additional feature is the ability to work with data stored directly in an external database. The benefits of doing this are that the data can be managed natively in a relational database, queries can be conducted on that database, and only the results of the query returned.</p>
<p>This addresses a common problem with R in that all operations are conducted in memory and thus the amount of data you can work with is limited by available memory. The database connections essentially remove that limitation in that you can have a database of many 100s GB, conduct queries on it directly, and pull back just what you need for analysis in R.</p>
<div id="selecting-columns-and-filtering-rows" class="section level3">
<h3>Selecting columns and filtering rows</h3>
<p>We’re going to learn some of the most common <code>dplyr</code> functions: <code>select()</code>, <code>filter()</code>, <code>mutate()</code>, <code>group_by()</code>, and <code>summarize()</code>. To select columns of a data frame, use <code>select()</code>. The first argument to this function is the data frame (<code>surveys</code>), and the subsequent arguments are the columns to keep.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">selected_col <-<span class="st"> </span><span class="kw">select</span>(surveys, plot_id, species_id, weight)
<span class="kw">head</span>(selected_col)</code></pre></div>
<p>To choose rows, use <code>filter()</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">surveys1995 <-<span class="st"> </span><span class="kw">filter</span>(surveys, year ==<span class="st"> </span><span class="dv">1995</span>)
<span class="kw">head</span>(surveys1995)</code></pre></div>
</div>
<div id="pipes" class="section level3">
<h3>Pipes</h3>
<p>The <em>pipe</em> operator (<code>%>%</code>) from the magrittr package makes it easy to chain these actions together: the output of one function becomes the input of the next.</p>
<div class="sourceCode"><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></div>
<p>Another cumbersome bit of typing. In RStudio, type <kbd><code>Ctrl</code></kbd> + <kbd><code>Shift</code></kbd> + <kbd><code>M</code></kbd> and the <code>%>%</code> operator will be inserted.</p>
<p>In the above we use the pipe to send the <code>surveys</code> data set first through <code>filter</code>, to keep rows where <code>wgt</code> was less than 5, and then through <code>select</code> to keep the <code>species</code> and <code>sex</code> columns. When the data frame is being passed to the <code>filter()</code> and <code>select()</code> functions through a pipe, we don’t need to include it as an argument to these functions anymore.</p>
<p>If we wanted to create a new object with this smaller version of the data we could do so by assigning it a new name:</p>
<div class="sourceCode"><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>
<p>Note that the final data frame is the leftmost part of this expression.</p>
</div>
<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>
<!-- end challenge -->
</div>
<div id="mutate" class="section level3">
<h3>Mutate</h3>
<p>Frequently you’ll want to create new columns based on the values in existing columns, for example to do unit conversions, or find the ratio of values in two columns. For this we’ll use <code>mutate()</code>.</p>
<p>To create a new column of weight in kg:</p>
<div class="sourceCode"><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></div>
<p>If this runs off your screen and you just want to see the first few rows, you can use a pipe to view the <code>head()</code> of the data (pipes work with non-dplyr functions too, as long as the <code>dplyr</code> or <code>magrittr</code> packages are loaded).</p>
<div class="sourceCode"><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></div>
<p>The first few rows are full of NAs, so if we wanted to remove those we could insert a <code>filter()</code> in this chain:</p>
<div class="sourceCode"><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>
<p><code>is.na()</code> is a function that determines whether something is or is not an <code>NA</code>. The <code>!</code> symbol negates it, so we’re asking for everything that is not an <code>NA</code>.</p>
</div>
<div id="challenge-1" class="section level3">
<h3>Challenge</h3>
<p>Create a new dataframe from the survey data that meets the following criteria:</p>
<ul>
<li>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>).</li>
<li>In this <code>hindfoot_sqrt</code> column, there are no NA values and all values are < 3.</li>
</ul>
<p>Hint: think about how the commands should be ordered</p>
<!-- end challenge -->
</div>
<div id="split-apply-combine-data-analysis-and-the-summarize-function" class="section level3">
<h3>Split-apply-combine data analysis and the summarize() function</h3>
<p>Many data analysis tasks can be approached using the “split-apply-combine” paradigm: split the data into groups, apply some analysis to each group, and then combine the results. <code>dplyr</code> makes this very easy through the use of the <code>group_by()</code> function. <code>group_by()</code> splits the data into groups upon which some operations can be run. For example, if we wanted to group by sex and find the number of rows of data for each sex, we would do:</p>
<div class="sourceCode"><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></div>
<p>Here, <code>tally()</code> is the action applied to the groups created to <code>group_by()</code> and counts the total number of records for each category. <code>group_by()</code> is often used together with <code>summarize()</code> which collapses each group into a single-row summary of that group. So to view mean <code>weight</code> by sex:</p>
<div class="sourceCode"><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></div>
<p>You can group by multiple columns too:</p>
<div class="sourceCode"><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></div>
<p>It looks like most of these species were never weighed. We could then discard rows where <code>mean_weight</code> is <code>NA</code> with <code>filter()</code>:</p>
<div class="sourceCode"><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></div>
<p>Another thing we might do here is sort rows by <code>mean_weight</code>, using <code>arrange()</code>.</p>
<div class="sourceCode"><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></div>
<p>If you want them sorted from highest to lowest, use <code>desc()</code>.</p>
<div class="sourceCode"><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></div>
<p>Also note that you can include multiple summaries.</p>
<div class="sourceCode"><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>
<div id="challenge-2" class="section level3">
<h3>Challenge</h3>
<p>How many times was each <code>plot_type</code> surveyed?</p>
<!-- end challenge -->
</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>
<!-- end challenge -->
</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>
<p>Hint: Use <code>filter()</code> rather than <code>summarize()</code>.</p>
<!-- end challenge -->
</div>
<div id="a-bit-of-data-cleaning" class="section level3">
<h3>A bit of data cleaning</h3>
<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>
<div class="sourceCode"><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></div>
<p>There are a lot of species with low counts. Let’s remove the species with less than 10 counts.</p>
<div class="sourceCode"><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>
reduced <-<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></div>
<p>We might save this to a file:</p>
<div class="sourceCode"><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></div>
<p><a href="http://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf">Handy dplyr cheatsheet</a></p>
</div>
</div>
</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>