forked from datacarpentry/R-genomics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
04-dplyr.html
587 lines (516 loc) · 28 KB
/
04-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
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
<!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="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/bootstrap.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>
<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/font-awesome-5.0.13/css/fa-svg-with-js.css" rel="stylesheet" />
<script src="site_libs/font-awesome-5.0.13/js/fontawesome-all.min.js"></script>
<script src="site_libs/font-awesome-5.0.13/js/fa-v4-shims.min.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
a.sourceLine { display: inline-block; line-height: 1.25; }
a.sourceLine { pointer-events: none; color: inherit; text-decoration: inherit; }
a.sourceLine:empty { height: 1.2em; position: absolute; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
a.sourceLine { text-indent: -1em; padding-left: 1em; }
}
pre.numberSource a.sourceLine
{ position: relative; }
pre.numberSource a.sourceLine:empty
{ position: absolute; }
pre.numberSource a.sourceLine::before
{ content: attr(data-line-number);
position: absolute; left: -5em; text-align: right; vertical-align: baseline;
border: none; pointer-events: all;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
a.sourceLine::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</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>
<link rel="stylesheet" href="style.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;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 51px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 56px;
margin-top: -56px;
}
.section h2 {
padding-top: 56px;
margin-top: -56px;
}
.section h3 {
padding-top: 56px;
margin-top: -56px;
}
.section h4 {
padding-top: 56px;
margin-top: -56px;
}
.section h5 {
padding-top: 56px;
margin-top: -56px;
}
.section h6 {
padding-top: 56px;
margin-top: -56px;
}
</style>
<script>
// 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.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</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, '_').toLowerCase();
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = false;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
.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;
padding-left: 25px;
text-indent: 0;
}
.tocify .list-group-item {
border-radius: 0px;
}
.tocify-subheader {
display: inline;
}
.tocify-subheader .tocify-item {
font-size: 0.95em;
}
</style>
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-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"></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="00-before-we-start.html">Before we start</a>
</li>
<li>
<a href="01-intro-to-R.html">Intro to R</a>
</li>
<li>
<a href="02-starting-with-data.html">Starting with data</a>
</li>
<li>
<a href="03-data-frames.html">Data frames</a>
</li>
<li>
<a href="04-dplyr.html">The dplyr package</a>
</li>
<li>
<a href="05-data-visualization.html">Data visualization</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/data-lessons/R-genomics">
<span class="fa fa-github fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<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>
<hr />
<div id="data-manipulation-using-dplyr" class="section level1">
<h1>Data manipulation using dplyr</h1>
</div>
<div id="learning-objectives" class="section level1">
<h1>Learning Objectives</h1>
<ul>
<li>Describe what the dplyr package in R is used for.</li>
<li>Apply common dplyr functions to manipulate data in R.</li>
<li>Employ the ‘pipe’ operator to link together a sequence of functions.</li>
<li>Employ the ‘mutate’ function to apply other chosen functions to existing columns and create new columns of data.</li>
<li>Employ the ‘split-apply-combine’ concept to split the data into groups, apply analysis to each group, and combine the results.</li>
</ul>
<p>Bracket subsetting is handy, but it can be cumbersome and difficult to read, especially for complicated operations.</p>
<p>Enter <code>dplyr</code>.</p>
<p><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 in R. The functions we’ve been using, like <code>str()</code>, come built into R; packages give you access to more functions. You need to install a package and then load it to be able to use it.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb1-1" data-line-number="1"><span class="kw">install.packages</span>(<span class="st">"dplyr"</span>) ## install</a></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; I’d recommend choosing the RStudio mirror.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb2-1" data-line-number="1"><span class="kw">library</span>(<span class="st">"dplyr"</span>) ## load</a></code></pre></div>
<p>You only need to install a package once per computer, but you need to load it every time you open a new R session and want to use that package.</p>
<div id="what-is-dplyr" class="section level2">
<h2>What is dplyr?</h2>
<p>The package <code>dplyr</code> is a fairly new (2014) package that tries to provide 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>metadata</code>), and the subsequent arguments are the columns to keep.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb3-1" data-line-number="1"><span class="kw">select</span>(metadata, sample, clade, cit, genome_size)</a></code></pre></div>
<p>To choose rows, use <code>filter()</code>:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb4-1" data-line-number="1"><span class="kw">filter</span>(metadata, cit <span class="op">==</span><span class="st"> "plus"</span>)</a></code></pre></div>
<pre><code>## sample generation clade strain cit run genome_size
## 1 ZDB564 31500 Cit+ REL606 plus SRR098289 4.74
## 2 ZDB172 32000 Cit+ REL606 plus SRR098042 4.77
## 3 ZDB143 32500 Cit+ REL606 plus SRR098040 4.79
## 4 CZB152 33000 Cit+ REL606 plus SRR097977 4.80
## 5 CZB154 33000 Cit+ REL606 plus SRR098026 4.76
## 6 ZDB87 34000 C2 REL606 plus SRR098035 4.75
## 7 ZDB96 36000 Cit+ REL606 plus SRR098036 4.74
## 8 ZDB107 38000 Cit+ REL606 plus SRR098038 4.79
## 9 REL10979 40000 Cit+ REL606 plus SRR098029 4.78</code></pre>
</div>
<div id="pipes" class="section level3">
<h3>Pipes</h3>
<p>But what if you wanted to select and filter? There are three ways to do this: use intermediate steps, nested functions, or pipes. With the intermediate steps, you essentially create a temporary data frame and use that as input to the next function. This can clutter up your workspace with lots of objects. You can also nest functions (i.e. one function inside of another). This is handy, but can be difficult to read if too many functions are nested as the process from inside out. The last option, pipes, are a fairly recent addition to R. Pipes let you take the output of one function and send it directly to the next, which is useful when you need to many things to the same data set. Pipes in R look like <code>%>%</code> and are made available via the <code>magrittr</code> package installed as part of <code>dplyr</code>.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb6-1" data-line-number="1">metadata <span class="op">%>%</span></a>
<a class="sourceLine" id="cb6-2" data-line-number="2"><span class="st"> </span><span class="kw">filter</span>(cit <span class="op">==</span><span class="st"> "plus"</span>) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb6-3" data-line-number="3"><span class="st"> </span><span class="kw">select</span>(sample, generation, clade)</a></code></pre></div>
<pre><code>## sample generation clade
## 1 ZDB564 31500 Cit+
## 2 ZDB172 32000 Cit+
## 3 ZDB143 32500 Cit+
## 4 CZB152 33000 Cit+
## 5 CZB154 33000 Cit+
## 6 ZDB87 34000 C2
## 7 ZDB96 36000 Cit+
## 8 ZDB107 38000 Cit+
## 9 REL10979 40000 Cit+</code></pre>
<p>In the above we use the pipe to send the <code>metadata</code> data set first through <code>filter</code>, to keep rows where <code>cit</code> was equal to ‘plus’, and then through <code>select</code> to keep the <code>sample</code> and <code>generation</code> and <code>clade</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" id="cb8"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb8-1" data-line-number="1">meta_citplus <-<span class="st"> </span>metadata <span class="op">%>%</span></a>
<a class="sourceLine" id="cb8-2" data-line-number="2"><span class="st"> </span><span class="kw">filter</span>(cit <span class="op">==</span><span class="st"> "plus"</span>) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb8-3" data-line-number="3"><span class="st"> </span><span class="kw">select</span>(sample, generation, clade)</a>
<a class="sourceLine" id="cb8-4" data-line-number="4"></a>
<a class="sourceLine" id="cb8-5" data-line-number="5">meta_citplus</a></code></pre></div>
<pre><code>## sample generation clade
## 1 ZDB564 31500 Cit+
## 2 ZDB172 32000 Cit+
## 3 ZDB143 32500 Cit+
## 4 CZB152 33000 Cit+
## 5 CZB154 33000 Cit+
## 6 ZDB87 34000 C2
## 7 ZDB96 36000 Cit+
## 8 ZDB107 38000 Cit+
## 9 REL10979 40000 Cit+</code></pre>
<blockquote>
<h3 id="challenge" class="challenge">Challenge</h3>
<p>Using pipes, subset the data to include rows where the clade is ‘Cit+’. Retain columns <code>sample</code>, <code>cit</code>, and <code>genome_size.</code></p>
</blockquote>
</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 genome size in bp:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb10-1" data-line-number="1">metadata <span class="op">%>%</span></a>
<a class="sourceLine" id="cb10-2" data-line-number="2"><span class="st"> </span><span class="kw">mutate</span>(<span class="dt">genome_bp =</span> genome_size <span class="op">*</span><span class="fl">1e6</span>)</a></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" id="cb11"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb11-1" data-line-number="1">metadata <span class="op">%>%</span></a>
<a class="sourceLine" id="cb11-2" data-line-number="2"><span class="st"> </span><span class="kw">mutate</span>(<span class="dt">genome_bp =</span> genome_size <span class="op">*</span><span class="fl">1e6</span>) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb11-3" data-line-number="3"><span class="st"> </span>head</a></code></pre></div>
<p>The row has a NA value for clade, so if we wanted to remove those we could insert a <code>filter()</code> in this chain:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb12-1" data-line-number="1">metadata <span class="op">%>%</span></a>
<a class="sourceLine" id="cb12-2" data-line-number="2"><span class="st"> </span><span class="kw">mutate</span>(<span class="dt">genome_bp =</span> genome_size <span class="op">*</span><span class="fl">1e6</span>) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb12-3" data-line-number="3"><span class="st"> </span><span class="kw">filter</span>(<span class="op">!</span><span class="kw">is.na</span>(clade)) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb12-4" data-line-number="4"><span class="st"> </span>head</a></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="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, which splits the data into groups. When the data is grouped in this way <code>summarize()</code> can be used to collapse each group into a single-row summary. <code>summarize()</code> does this by applying an aggregating or summary function to each group. For example, if we wanted to group by citrate-using mutant status and find the number of rows of data for each status, we would do:</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb13-1" data-line-number="1">metadata <span class="op">%>%</span></a>
<a class="sourceLine" id="cb13-2" data-line-number="2"><span class="st"> </span><span class="kw">group_by</span>(cit) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb13-3" data-line-number="3"><span class="st"> </span><span class="kw">summarize</span>(<span class="kw">n</span>())</a></code></pre></div>
<pre><code>## # A tibble: 3 x 2
## cit `n()`
## <fct> <int>
## 1 minus 9
## 2 plus 9
## 3 unknown 12</code></pre>
<p>Here the summary function used was <code>n()</code> to find the count for each group. We can also apply many other functions to individual columns to get other summary statistics. For example, in the R base package we can use built-in functions like <code>mean</code>, <code>median</code>, <code>min</code>, and <code>max</code>. By default, all <strong>R functions operating on vectors that contains missing data will return NA</strong>. It’s a way to make sure that users know they have missing data, and make a conscious decision on how to deal with it. When dealing with simple statistics like the mean, the easiest way to ignore <code>NA</code> (the missing data) is to use <code>na.rm=TRUE</code> (<code>rm</code> stands for remove).</p>
<p>So to view mean <code>genome_size</code> by mutant status:</p>
<div class="sourceCode" id="cb15"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb15-1" data-line-number="1">metadata <span class="op">%>%</span></a>
<a class="sourceLine" id="cb15-2" data-line-number="2"><span class="st"> </span><span class="kw">group_by</span>(cit) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb15-3" data-line-number="3"><span class="st"> </span><span class="kw">summarize</span>(<span class="dt">mean_size =</span> <span class="kw">mean</span>(genome_size, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>))</a></code></pre></div>
<pre><code>## # A tibble: 3 x 2
## cit mean_size
## <fct> <dbl>
## 1 minus 4.61
## 2 plus 4.77
## 3 unknown 4.62</code></pre>
<p>You can group by multiple columns too:</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb17-1" data-line-number="1">metadata <span class="op">%>%</span></a>
<a class="sourceLine" id="cb17-2" data-line-number="2"><span class="st"> </span><span class="kw">group_by</span>(cit, clade) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb17-3" data-line-number="3"><span class="st"> </span><span class="kw">summarize</span>(<span class="dt">mean_size =</span> <span class="kw">mean</span>(genome_size, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>))</a></code></pre></div>
<pre><code>## # A tibble: 13 x 3
## # Groups: cit [?]
## cit clade mean_size
## <fct> <fct> <dbl>
## 1 minus C1 4.61
## 2 minus C2 4.62
## 3 minus C3 4.61
## 4 minus Cit+ 4.6
## 5 plus C2 4.75
## 6 plus Cit+ 4.77
## 7 unknown (C1,C2) 4.62
## 8 unknown C1 4.63
## 9 unknown C2 4.62
## 10 unknown C3 4.59
## 11 unknown UC 4.62
## 12 unknown unknown 4.62
## 13 unknown <NA> 4.62</code></pre>
<p>Looks like for one of these clones, the clade is missing. We could then discard those rows using <code>filter()</code>:</p>
<div class="sourceCode" id="cb19"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb19-1" data-line-number="1">metadata <span class="op">%>%</span></a>
<a class="sourceLine" id="cb19-2" data-line-number="2"><span class="st"> </span><span class="kw">group_by</span>(cit, clade) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb19-3" data-line-number="3"><span class="st"> </span><span class="kw">summarize</span>(<span class="dt">mean_size =</span> <span class="kw">mean</span>(genome_size, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb19-4" data-line-number="4"><span class="st"> </span><span class="kw">filter</span>(<span class="op">!</span><span class="kw">is.na</span>(clade))</a></code></pre></div>
<p>All of a sudden this isn’t running off the screen anymore. That’s because <code>dplyr</code> has changed our <code>data.frame</code> to a <code>tbl_df</code>. This is a data structure that’s very similar to a data frame; for our purposes the only difference is that it won’t automatically show tons of data going off the screen.</p>
<p>You can also summarize multiple variables at the same time:</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb20-1" data-line-number="1">metadata <span class="op">%>%</span></a>
<a class="sourceLine" id="cb20-2" data-line-number="2"><span class="st"> </span><span class="kw">group_by</span>(cit, clade) <span class="op">%>%</span></a>
<a class="sourceLine" id="cb20-3" data-line-number="3"><span class="st"> </span><span class="kw">summarize</span>(<span class="dt">mean_size =</span> <span class="kw">mean</span>(genome_size, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>),</a>
<a class="sourceLine" id="cb20-4" data-line-number="4"> <span class="dt">min_generation =</span> <span class="kw">min</span>(generation))</a></code></pre></div>
<p><a href="http://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf">Handy dplyr cheatsheet</a></p>
<p><em>Much of this lesson was copied or adapted from Jeff Hollister’s <a href="http://usepa.github.io/introR/2015/01/14/03-Clean/">materials</a></em></p>
</div>
</div>
</div>
<hr/>
<p><a href="http://datacarpentry.org/">Data Carpentry</a>,
2017-2018. <a href="LICENSE.html">License</a>. <a href="CONTRIBUTING.html">Contributing</a>. <br/>
Questions? Feedback?
Please <a href="https://github.com/datacarpentry/R-genomics/issues/new">file
an issue on GitHub</a>. <br/> On
Twitter: <a href="https://twitter.com/datacarpentry">@datacarpentry</a></p>
</div>
</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://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>