-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek9-data-wrangling.html
1532 lines (1415 loc) · 59.9 KB
/
week9-data-wrangling.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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Week 9: Intro to piping and tidyverse data wrangling</title>
<script src="site_libs/header-attrs-2.7/header-attrs.js"></script>
<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/readable.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>
<style>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;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<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/highlightjs-9.12.0/textmate.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-5.1.0/css/all.css" rel="stylesheet" />
<link href="site_libs/font-awesome-5.1.0/css/v4-shims.css" rel="stylesheet" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// 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.tab('show');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.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;
}
.tocify .list-group-item {
border-radius: 0px;
}
.tocify-subheader {
display: inline;
}
.tocify-subheader .tocify-item {
font-size: 0.95em;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row">
<div class="col-sm-12 col-md-4 col-lg-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-sm-12 col-md-8 col-lg-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">RWorkflow</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="set-up.html">
<span class="fas fa-clone"></span>
Set-up
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class="fab fa-git"></span>
Git
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="intro-git.html">
<span class="fab fa-github"></span>
Intro to Git + GitHub
</a>
</li>
<li>
<a href="more-git.html">
<span class="fab fa-github-alt"></span>
More Git + GitHub
</a>
</li>
<li>
<a href="gitlab-to-github.html">
<span class="fas fa-truck-moving"></span>
GitLab to GitHub
</a>
</li>
<li>
<a href="websites.html">
<span class="fab fa-chrome"></span>
Websites with GitHub
</a>
</li>
<li>
<a href="jekyll.html">
<span class="fas fa-sitemap"></span>
Dynamic Websites with Jekyll and GitHub
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class="fas fa-file"></span>
RMarkdown
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="week3-RMarkdown.html">
<span class="fas fa-file"></span>
R Markdown for Reports
</a>
</li>
<li>
<a href="bookdown.html">
<span class="fas fa-book"></span>
Bookdown
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class="fas fa-archive"></span>
R Packages
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="week4-packages.html">
<span class="fas fa-archive"></span>
R Packaging with RStudio
</a>
</li>
<li>
<a href="week5-roxygen.html">
<span class="fas fa-question-circle"></span>
Roxygen documentation
</a>
</li>
<li>
<a href="week6-more-packages.html">
<span class="fas fa-folder"></span>
More package stuff
</a>
</li>
<li>
<a href="shiny.html">
<span class="fas fa-gamepad"></span>
Shiny GUIs
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class="fas fa-broom"></span>
Tidyverse
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="week8-ggplot2.html">
<span class="fas fa-image"></span>
ggplot2
</a>
</li>
<li>
<a href="week9-data-wrangling.html">
<span class="fas fa-broom"></span>
tidyr
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
More
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="links.html">Tutorials</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/RVerse-Tutorials/RWorkflow">
<span class="fab fa-github"></span>
Repo
</a>
</li>
<li>
<a href="search.html">Search</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">Week 9: Intro to piping and tidyverse data wrangling</h1>
</div>
<p>This week I will give a brief introduction to piping and data wrangling with tidyr and tidyverse verbs. If you want to learn more, there are many resources on the web. I like <a href="https://dcl-wrangle.stanford.edu/">this course book</a> as a beginning, <a href="https://cengel.github.io/R-data-wrangling/">this course</a> goes into more depth, and <a href="https://r4ds.had.co.nz/">R for Data Science</a> has much more.</p>
<p>Today’s goal is to teach you 6 data “verbs” that are easy to use and that will cover many of your data-wrangling needs.</p>
<pre class="r"><code>library(dplyr)
library(tidyr)
library(ggplot2)</code></pre>
<div id="piping" class="section level1">
<h1>Piping</h1>
<p>You already use the concept of “piping”, but you do it with parentheses. Your pipe in this case goes from inside to outside.</p>
<pre><code>fun4(fun3(fun2(fun1(x))))</code></pre>
<p><code>x</code> is our initial object. We apply <code>fun1()</code> to that. Then that result goes into <code>fun2()</code>. The result of that goes into <code>fun3()</code>. etc. “Pipe” is referring to the flow of information, the “goes into” part.</p>
<p>This has many problems.</p>
<ul>
<li>You will lose track of your parentheses and waste much time sorting out where you lost one of your parentheses.</li>
<li>You are limited in how many levels you can add without your code being unreadable as it stretches quickly to multiple lines.</li>
<li>We don’t read inside to outside though from our math education, we are used to that (sort of).</li>
</ul>
<p>Piping is just a different way to write the same thing but left to right like we read (in English).</p>
<pre><code>x %>% fun1() %>% fun2() %>% fun3() %>% fun4()</code></pre>
<p>Example:</p>
<pre class="r"><code>1:10 %>% sqrt() %>% mean() %>% round(digits=1) </code></pre>
<pre><code>## [1] 2.2</code></pre>
<p>That’s the same as</p>
<pre class="r"><code>round(mean(sqrt(1:10)),digits=1) </code></pre>
<pre><code>## [1] 2.2</code></pre>
<div id="upsides" class="section level2">
<h2>Upsides</h2>
<ul>
<li>It is used a lot in the tidyverse so you should be aware of how it works.</li>
<li>It works well in the tidyverse.</li>
<li>Can be more readable.</li>
<li>Makes it easy to avoid intermediate variables (<code>tmp</code> and <code>foo</code>).</li>
</ul>
</div>
<div id="downsides" class="section level2">
<h2>Downsides</h2>
<ul>
<li>It’s is easy to write code that is hard to understand. It tends to hide where the object on the left is going to in the function on the right.</li>
</ul>
<p>So you see code like this</p>
<pre class="r"><code>fun <- function(a=1, b=10){c(max(a), min(b))}
a <- 2:10
a %>% fun(a^2)</code></pre>
<pre><code>## [1] 10 4</code></pre>
<p>and you have to go research <code>fun</code> to discover that this is <code>fun(a=a, b=a^2)</code>.</p>
<p>This kind of mistake is so easy to make. You want say, <code>rnorm(n=a)</code>, and accidentally write that in your pipe.</p>
<pre class="r"><code>a <- 3
a %>% rnorm(n=a)</code></pre>
<pre><code>## [1] 2.029148 0.903325 3.851952</code></pre>
<pre class="r"><code>a %>% rnorm()</code></pre>
<pre><code>## [1] -0.9141921 1.9386994 -0.3330177</code></pre>
<p>The left flows into the first function spot, UNLESS you specified that and then it flows to the second or third or whatever is “open”.</p>
<ul>
<li><p>You can spend hours trying to solve your piping issue when you could immediately write down code using intermediate values.</p></li>
<li><p>It’s really slow.</p></li>
</ul>
<pre class="r"><code>library(microbenchmark)
bm <- microbenchmark(1:10 %>% sqrt() %>% mean() %>% round(digits=1), round(mean(sqrt(1:10)),digits=1) )
ggplot2::autoplot(bm)</code></pre>
<p><img src="week9-data-wrangling_files/figure-html/unnamed-chunk-6-1.png" width="672" /></p>
<ul>
<li>You must stay hyper-alert as to the names in the data frame you are working with. You might not have created this data frame. This may be a function you wrote to take any data frame from a user…. Otherwise, bad things like this can happen.</li>
</ul>
<pre class="r"><code>fun <- function(x, cyl=1){
x %>% transform(new = mpg^cyl) %>% select(mpg, new)
}</code></pre>
<p>Works great!</p>
<pre class="r"><code>df <- data.frame(mpg=runif(10, 10, 30))
fun(df, cyl=0.5)</code></pre>
<pre><code>## mpg new
## 1 15.15951 3.893521
## 2 26.76402 5.173396
## 3 17.31408 4.161019
## 4 17.62835 4.198613
## 5 26.68647 5.165895
## 6 13.99436 3.740903
## 7 13.71048 3.702767
## 8 15.80307 3.975307
## 9 17.29457 4.158674
## 10 15.84034 3.979992</code></pre>
<p>Why, why? It didn’t complain but this is wrong!</p>
<pre class="r"><code>fun(mtcars[1:5,], cyl=0.5)</code></pre>
<pre><code>## mpg new
## Mazda RX4 21.0 8.576612e+07
## Mazda RX4 Wag 21.0 8.576612e+07
## Datsun 710 22.8 2.702336e+05
## Hornet 4 Drive 21.4 9.604674e+07
## Hornet Sportabout 18.7 1.495316e+10</code></pre>
</div>
</div>
<div id="tidyverse-verbs" class="section level1">
<h1>Tidyverse verbs</h1>
<p>Read up on tidyverse verbs <a href="https://dplyr.tidyverse.org/">here</a>.</p>
<p>NOTE:</p>
<ul>
<li>I am using piping because that is how you will see these verbs used in online material. They are just functions and you do not need to use them with piping.</li>
<li>They are very slow. For loops are not the place for these functions. <code>apply()</code> in base R is much faster.</li>
<li>Tidyverse is maturing and the semantics across functions is not quite the same. Careful.</li>
</ul>
<div id="workflow" class="section level2">
<h2>Workflow</h2>
<pre><code>data.frame %>%
select columns or filter rows %>%
summarize or mutate</code></pre>
<pre><code>data.frame %>%
group data %>%
summarize or mutate</code></pre>
<p>Verbs that we will learn:</p>
<ul>
<li><code>select()</code> select columns</li>
<li><code>filter()</code> select rows</li>
<li><code>group_by()</code> apply the function differently within groups.</li>
<li><code>summarize()</code> apply function over columns -> fewer rows. Like <code>apply(df,2,function)</code></li>
<li><code>mutate()</code> apply function to columns and make new column. Like <code>apply(df,1,function)</code></li>
</ul>
<p>What we won’t learn: applying a function across a group of columns. See ?across to learn about that.</p>
</div>
<div id="selecting-and-filtering" class="section level2">
<h2>Selecting and filtering</h2>
<pre><code>data.frame %>%
select or filter</code></pre>
<div id="select" class="section level3">
<h3><code>select()</code></h3>
<p>Select columns.</p>
<pre class="r"><code>head(mtcars)</code></pre>
<pre><code>## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1</code></pre>
<pre class="r"><code>mtcars %>% select(mpg)</code></pre>
<pre><code>## mpg
## Mazda RX4 21.0
## Mazda RX4 Wag 21.0
## Datsun 710 22.8
## Hornet 4 Drive 21.4
## Hornet Sportabout 18.7
## Valiant 18.1
## Duster 360 14.3
## Merc 240D 24.4
## Merc 230 22.8
## Merc 280 19.2
## Merc 280C 17.8
## Merc 450SE 16.4
## Merc 450SL 17.3
## Merc 450SLC 15.2
## Cadillac Fleetwood 10.4
## Lincoln Continental 10.4
## Chrysler Imperial 14.7
## Fiat 128 32.4
## Honda Civic 30.4
## Toyota Corolla 33.9
## Toyota Corona 21.5
## Dodge Challenger 15.5
## AMC Javelin 15.2
## Camaro Z28 13.3
## Pontiac Firebird 19.2
## Fiat X1-9 27.3
## Porsche 914-2 26.0
## Lotus Europa 30.4
## Ford Pantera L 15.8
## Ferrari Dino 19.7
## Maserati Bora 15.0
## Volvo 142E 21.4</code></pre>
<pre class="r"><code>mtcars %>% select(-mpg, -qsec, -gear, -cyl)</code></pre>
<pre><code>## disp hp drat wt vs am carb
## Mazda RX4 160.0 110 3.90 2.620 0 1 4
## Mazda RX4 Wag 160.0 110 3.90 2.875 0 1 4
## Datsun 710 108.0 93 3.85 2.320 1 1 1
## Hornet 4 Drive 258.0 110 3.08 3.215 1 0 1
## Hornet Sportabout 360.0 175 3.15 3.440 0 0 2
## Valiant 225.0 105 2.76 3.460 1 0 1
## Duster 360 360.0 245 3.21 3.570 0 0 4
## Merc 240D 146.7 62 3.69 3.190 1 0 2
## Merc 230 140.8 95 3.92 3.150 1 0 2
## Merc 280 167.6 123 3.92 3.440 1 0 4
## Merc 280C 167.6 123 3.92 3.440 1 0 4
## Merc 450SE 275.8 180 3.07 4.070 0 0 3
## Merc 450SL 275.8 180 3.07 3.730 0 0 3
## Merc 450SLC 275.8 180 3.07 3.780 0 0 3
## Cadillac Fleetwood 472.0 205 2.93 5.250 0 0 4
## Lincoln Continental 460.0 215 3.00 5.424 0 0 4
## Chrysler Imperial 440.0 230 3.23 5.345 0 0 4
## Fiat 128 78.7 66 4.08 2.200 1 1 1
## Honda Civic 75.7 52 4.93 1.615 1 1 2
## Toyota Corolla 71.1 65 4.22 1.835 1 1 1
## Toyota Corona 120.1 97 3.70 2.465 1 0 1
## Dodge Challenger 318.0 150 2.76 3.520 0 0 2
## AMC Javelin 304.0 150 3.15 3.435 0 0 2
## Camaro Z28 350.0 245 3.73 3.840 0 0 4
## Pontiac Firebird 400.0 175 3.08 3.845 0 0 2
## Fiat X1-9 79.0 66 4.08 1.935 1 1 1
## Porsche 914-2 120.3 91 4.43 2.140 0 1 2
## Lotus Europa 95.1 113 3.77 1.513 1 1 2
## Ford Pantera L 351.0 264 4.22 3.170 0 1 4
## Ferrari Dino 145.0 175 3.62 2.770 0 1 6
## Maserati Bora 301.0 335 3.54 3.570 0 1 8
## Volvo 142E 121.0 109 4.11 2.780 1 1 2</code></pre>
<pre class="r"><code>mtcars %>% select(disp:qsec)</code></pre>
<pre><code>## disp hp drat wt qsec
## Mazda RX4 160.0 110 3.90 2.620 16.46
## Mazda RX4 Wag 160.0 110 3.90 2.875 17.02
## Datsun 710 108.0 93 3.85 2.320 18.61
## Hornet 4 Drive 258.0 110 3.08 3.215 19.44
## Hornet Sportabout 360.0 175 3.15 3.440 17.02
## Valiant 225.0 105 2.76 3.460 20.22
## Duster 360 360.0 245 3.21 3.570 15.84
## Merc 240D 146.7 62 3.69 3.190 20.00
## Merc 230 140.8 95 3.92 3.150 22.90
## Merc 280 167.6 123 3.92 3.440 18.30
## Merc 280C 167.6 123 3.92 3.440 18.90
## Merc 450SE 275.8 180 3.07 4.070 17.40
## Merc 450SL 275.8 180 3.07 3.730 17.60
## Merc 450SLC 275.8 180 3.07 3.780 18.00
## Cadillac Fleetwood 472.0 205 2.93 5.250 17.98
## Lincoln Continental 460.0 215 3.00 5.424 17.82
## Chrysler Imperial 440.0 230 3.23 5.345 17.42
## Fiat 128 78.7 66 4.08 2.200 19.47
## Honda Civic 75.7 52 4.93 1.615 18.52
## Toyota Corolla 71.1 65 4.22 1.835 19.90
## Toyota Corona 120.1 97 3.70 2.465 20.01
## Dodge Challenger 318.0 150 2.76 3.520 16.87
## AMC Javelin 304.0 150 3.15 3.435 17.30
## Camaro Z28 350.0 245 3.73 3.840 15.41
## Pontiac Firebird 400.0 175 3.08 3.845 17.05
## Fiat X1-9 79.0 66 4.08 1.935 18.90
## Porsche 914-2 120.3 91 4.43 2.140 16.70
## Lotus Europa 95.1 113 3.77 1.513 16.90
## Ford Pantera L 351.0 264 4.22 3.170 14.50
## Ferrari Dino 145.0 175 3.62 2.770 15.50
## Maserati Bora 301.0 335 3.54 3.570 14.60
## Volvo 142E 121.0 109 4.11 2.780 18.60</code></pre>
<pre class="r"><code>mtcars %>% select(!disp:qsec)</code></pre>
<pre><code>## mpg cyl vs am gear carb
## Mazda RX4 21.0 6 0 1 4 4
## Mazda RX4 Wag 21.0 6 0 1 4 4
## Datsun 710 22.8 4 1 1 4 1
## Hornet 4 Drive 21.4 6 1 0 3 1
## Hornet Sportabout 18.7 8 0 0 3 2
## Valiant 18.1 6 1 0 3 1
## Duster 360 14.3 8 0 0 3 4
## Merc 240D 24.4 4 1 0 4 2
## Merc 230 22.8 4 1 0 4 2
## Merc 280 19.2 6 1 0 4 4
## Merc 280C 17.8 6 1 0 4 4
## Merc 450SE 16.4 8 0 0 3 3
## Merc 450SL 17.3 8 0 0 3 3
## Merc 450SLC 15.2 8 0 0 3 3
## Cadillac Fleetwood 10.4 8 0 0 3 4
## Lincoln Continental 10.4 8 0 0 3 4
## Chrysler Imperial 14.7 8 0 0 3 4
## Fiat 128 32.4 4 1 1 4 1
## Honda Civic 30.4 4 1 1 4 2
## Toyota Corolla 33.9 4 1 1 4 1
## Toyota Corona 21.5 4 1 0 3 1
## Dodge Challenger 15.5 8 0 0 3 2
## AMC Javelin 15.2 8 0 0 3 2
## Camaro Z28 13.3 8 0 0 3 4
## Pontiac Firebird 19.2 8 0 0 3 2
## Fiat X1-9 27.3 4 1 1 4 1
## Porsche 914-2 26.0 4 0 1 5 2
## Lotus Europa 30.4 4 1 1 5 2
## Ford Pantera L 15.8 8 0 1 5 4
## Ferrari Dino 19.7 6 0 1 5 6
## Maserati Bora 15.0 8 0 1 5 8
## Volvo 142E 21.4 4 1 1 4 2</code></pre>
<pre class="r"><code>df %>% select(where(is.numeric))</code></pre>
<pre><code>## mpg
## 1 15.15951
## 2 26.76402
## 3 17.31408
## 4 17.62835
## 5 26.68647
## 6 13.99436
## 7 13.71048
## 8 15.80307
## 9 17.29457
## 10 15.84034</code></pre>
</div>
<div id="filter" class="section level3">
<h3><code>filter()</code></h3>
<p>Select rows.</p>
<pre class="r"><code>mtcars %>% filter(cyl==4)</code></pre>
<pre><code>## mpg cyl disp hp drat wt qsec vs am gear carb
## Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
## Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
## Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
## Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
## Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
## Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
## Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
## Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
## Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
## Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
## Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2</code></pre>
<p>Same as <code>subset(df, cyl==4)</code> or <code>df[df$cyl==4,]</code></p>
<pre class="r"><code>mtcars %>% filter(cyl==4, hp>90)</code></pre>
<pre><code>## mpg cyl disp hp drat wt qsec vs am gear carb
## Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
## Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
## Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
## Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
## Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
## Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2</code></pre>
<p>Same as <code>subset(df, cyl==4 & hp>90)</code> or <code>df[df$cyl==4 & df$hp>90,]</code>.</p>
</div>
</div>
<div id="summarize" class="section level2">
<h2><code>summarize()</code></h2>
<p><code>summarize()</code> summarizes down columns and leads to fewer rows. <strong>You must tell it the columns to work on.</strong></p>
<pre><code>data.frame %>%
summarize</code></pre>
<p>Apply a function to columns.</p>
<pre class="r"><code>mtcars %>%
summarize(mean.wt=mean(wt))</code></pre>
<pre><code>## mean.wt
## 1 3.21725</code></pre>
<p>I can add on more functions.</p>
<pre class="r"><code>mtcars %>%
summarize(mean.wt=mean(wt)) %>%
round(digits=2)</code></pre>
<pre><code>## mean.wt
## 1 3.22</code></pre>
<p>Same as</p>
<pre class="r"><code>round(mean(mtcars$wt), digits=2)</code></pre>
<pre><code>## [1] 3.22</code></pre>
<p>You can specify multiple columns. You have to put in <code>c()</code> in this case.</p>
<pre class="r"><code>mtcars %>%
summarize(mean.wt=mean(c(mpg, hp)))</code></pre>
<pre><code>## mean.wt
## 1 83.38906</code></pre>
<p>Same as</p>
<pre class="r"><code>mean(c(mtcars$mpg, mtcars$hp))</code></pre>
<pre><code>## [1] 83.38906</code></pre>
<p>Sadly this does NOT work for specifying a range. It computes something but not what you’d think. <strong>This is the <code>apply across columns</code> case.</strong> Read up on that in <code>?across</code>.</p>
<pre class="r"><code>mtcars %>%
summarize(mean.wt=mean(mpg:hp))</code></pre>
<pre><code>## Warning in mpg:hp: numerical expression has 32 elements: only the first used
## Warning in mpg:hp: numerical expression has 32 elements: only the first used</code></pre>
<pre><code>## mean.wt
## 1 65.5</code></pre>
<p>This is computing the mean of this:</p>
<pre class="r"><code>mtcars[1,"mpg"]:mtcars[1,"hp"]</code></pre>
<pre><code>## [1] 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
## [20] 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
## [39] 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
## [58] 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
## [77] 97 98 99 100 101 102 103 104 105 106 107 108 109 110</code></pre>
<p>which is</p>
<pre class="r"><code>mean(mtcars[1,"mpg"]:mtcars[1,"hp"])</code></pre>
<pre><code>## [1] 65.5</code></pre>
</div>
<div id="summarize-by-column" class="section level2">
<h2><code>summarize()</code> by column</h2>
<p><code>summarize_all()</code> and <code>summarize_at()</code></p>
<p>Apply to a range of columns or all columns. Note the <code>_at()</code> and <code>_all()</code> functions have been superseded with <code>across()</code> but I find <code>across()</code> really cumbersome. I personally would use <code>select()</code> and <code>summarize_all()</code>.</p>
<pre class="r"><code>mtcars %>% summarize_at(vars(mpg:hp), mean)</code></pre>
<pre><code>## mpg cyl disp hp
## 1 20.09062 6.1875 230.7219 146.6875</code></pre>
<pre><code>data.frame %>%
select columns %>%
use summarize_all()</code></pre>
<pre class="r"><code>mtcars %>%
select(mpg:hp) %>%
summarize_all(mean)</code></pre>
<pre><code>## mpg cyl disp hp
## 1 20.09062 6.1875 230.7219 146.6875</code></pre>
<pre class="r"><code>apply(mtcars[,1:4],2,mean)</code></pre>
<pre><code>## mpg cyl disp hp
## 20.09062 6.18750 230.72188 146.68750</code></pre>
<p><code>summarize_all()</code> is less picky than <code>apply()</code></p>
<pre class="r"><code>df <- mtcars[,1:3]; df$label="test"
df %>% summarize_all(mean)</code></pre>
<pre><code>## Warning in mean.default(label): argument is not numeric or logical: returning NA</code></pre>
<pre><code>## mpg cyl disp label
## 1 20.09062 6.1875 230.7219 NA</code></pre>
<p>while <code>apply()</code> gives all NA.</p>
<pre class="r"><code>apply(df,2,mean)</code></pre>
<pre><code>## Warning in mean.default(newX[, i], ...): argument is not numeric or logical:
## returning NA
## Warning in mean.default(newX[, i], ...): argument is not numeric or logical:
## returning NA
## Warning in mean.default(newX[, i], ...): argument is not numeric or logical:
## returning NA
## Warning in mean.default(newX[, i], ...): argument is not numeric or logical:
## returning NA</code></pre>
<pre><code>## mpg cyl disp label
## NA NA NA NA</code></pre>
<p>Another example.</p>
<pre><code>data.frame %>%
select rows %>%
select columns %>%
use summarize_all() verb to apply %>%
format with round()</code></pre>
<pre class="r"><code>mtcars %>%
filter(cyl==4) %>%
select(mpg:hp) %>%
summarize_all(mean) %>%
round(digits=2) %>%
paste(collapse=" -- ")</code></pre>
<pre><code>## [1] "26.66 -- 4 -- 105.14 -- 82.64"</code></pre>
</div>
<div id="summarize-by-group" class="section level2">
<h2><code>summarize()</code> by group</h2>
<pre><code>data.frame %>%
define groups %>%
apply summarize within groups</code></pre>
<pre class="r"><code>df2 <- data.frame(id=paste0(rep("s",8),1:2),
pop=paste0(rep("r",8),rep(1:2,each=4)),
Week1=rnorm(8), Week2=rnorm(8), Week3=rnorm(8), Week4=rnorm(8))
head(df2)</code></pre>
<pre><code>## id pop Week1 Week2 Week3 Week4
## 1 s1 r1 -0.83551483 1.43965277 1.6664183 -1.1372446
## 2 s2 r1 -1.63488346 0.94898124 -0.6758438 0.4264061
## 3 s1 r1 -0.04529889 0.57412587 -1.1827151 -0.2683061
## 4 s2 r1 -0.19604077 0.01420002 1.2047887 -0.8967390
## 5 s1 r2 -0.71715376 -1.28082258 -0.8366131 -0.1310937
## 6 s2 r2 -0.78223915 -1.39280749 1.1294121 -1.2896710</code></pre>
<p>The <code>group_by()</code> function allows you to do more complicated things. Take the mean by pop.</p>
<pre class="r"><code>df2 %>% group_by(pop) %>% summarize_all(mean)</code></pre>
<pre><code>## Warning in mean.default(id): argument is not numeric or logical: returning NA
## Warning in mean.default(id): argument is not numeric or logical: returning NA</code></pre>
<pre><code>## # A tibble: 2 x 6
## pop id Week1 Week2 Week3 Week4
## * <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 r1 NA -0.678 0.744 0.253 -0.469
## 2 r2 NA 0.0901 -0.682 0.607 -0.676</code></pre>
<pre class="r"><code>apply(df2[df2$pop=="r1",3:6],2,mean)</code></pre>
<pre><code>## Week1 Week2 Week3 Week4
## -0.6779345 0.7442400 0.2531620 -0.4689709</code></pre>
<p>Take the mean for all weeks by pop and id. Notice that I have to specify columns for <code>summarize()</code>.</p>
<pre class="r"><code>df2 %>%
group_by(pop, id) %>%
summarize(mean=mean(c(Week1, Week2, Week3, Week4)))</code></pre>
<pre><code>## `summarise()` has grouped output by 'pop'. You can override using the `.groups` argument.</code></pre>
<pre><code>## # A tibble: 4 x 3
## # Groups: pop [2]
## pop id mean
## <chr> <chr> <dbl>
## 1 r1 s1 0.0264
## 2 r1 s2 -0.101
## 3 r2 s1 -0.480
## 4 r2 s2 0.149</code></pre>
</div>
<div id="combine-group-and-select" class="section level2">
<h2>Combine group and select</h2>
<p>Select based on properties. For some reason you have to wrap in <code>where()</code>.</p>
<pre class="r"><code>df2 %>% group_by(pop) %>%
select(where(is.numeric)) %>%
summarize_all(mean)</code></pre>
<pre><code>## Adding missing grouping variables: `pop`</code></pre>
<pre><code>## # A tibble: 2 x 5
## pop Week1 Week2 Week3 Week4
## * <chr> <dbl> <dbl> <dbl> <dbl>
## 1 r1 -0.678 0.744 0.253 -0.469
## 2 r2 0.0901 -0.682 0.607 -0.676</code></pre>
<p>Select based on name.</p>
<pre class="r"><code>df2 %>% group_by(pop) %>%
select(ends_with("2")) %>%
summarize_all(mean)</code></pre>
<pre><code>## Adding missing grouping variables: `pop`</code></pre>
<pre><code>## # A tibble: 2 x 2
## pop Week2
## * <chr> <dbl>
## 1 r1 0.744
## 2 r2 -0.682</code></pre>
</div>
<div id="mutate" class="section level2">
<h2><code>mutate()</code></h2>
<p>Apply a function across rows and return a new column. Like <code>apply(df,1,fun)</code>.</p>
<pre class="r"><code>mtcars %>%
select(mpg:wt) %>%
mutate(wt.hp=wt/hp)</code></pre>
<pre><code>## mpg cyl disp hp drat wt wt.hp
## Mazda RX4 21.0 6 160.0 110 3.90 2.620 0.02381818
## Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 0.02613636
## Datsun 710 22.8 4 108.0 93 3.85 2.320 0.02494624
## Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 0.02922727
## Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 0.01965714
## Valiant 18.1 6 225.0 105 2.76 3.460 0.03295238
## Duster 360 14.3 8 360.0 245 3.21 3.570 0.01457143
## Merc 240D 24.4 4 146.7 62 3.69 3.190 0.05145161
## Merc 230 22.8 4 140.8 95 3.92 3.150 0.03315789
## Merc 280 19.2 6 167.6 123 3.92 3.440 0.02796748
## Merc 280C 17.8 6 167.6 123 3.92 3.440 0.02796748