-
Notifications
You must be signed in to change notification settings - Fork 1
/
02_dplyr.html
732 lines (592 loc) · 16 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
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<title>Touring tidyverse</title>
<meta charset="utf-8" />
<link href="libs/remark-css/default.css" rel="stylesheet" />
<link href="libs/remark-css/default-fonts.css" rel="stylesheet" />
<link href="libs/countdown/countdown.css" rel="stylesheet" />
<script src="libs/countdown/countdown.js"></script>
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# Touring tidyverse
## dplyr
---
background-image: url(https://www.rstudio.com/wp-content/uploads/2015/01/dplyr-hexbin-logo.png)
background-size: 100px
background-position: 90% 8%
# dplyr
has three main goals:
1. Identify the most important data manipulation verbs and make them easy to use from R.
2. Provide blazing fast performance for in-memory data by writing key pieces in C++ (using Rcpp).
3. Use the same interface to work with data no matter where it's stored, whether in a data frame, a data table or database.
---
# Initial commit of dplyr
The year was 2012... (`2012-10-28 19:37` to be precise)
```
Package: plyr2
Type: Package
Title: Tools for splitting, applying and combining data
Version: 0.01
Author: Hadley Wickham <h.wickham@gmail.com>
Maintainer: Hadley Wickham <h.wickham@gmail.com>
Description: ddply on crack
Depends:
R (>= 2.15.1)
License: MIT
```
---
# 23 minutes later
```
Package: dplyr
Type: Package
Title: dplyr: a grammar of data manipulation
Version: 0.01
Author: Hadley Wickham <h.wickham@gmail.com>
Maintainer: Hadley Wickham <h.wickham@gmail.com>
Description: A fast, consistent tools for working with data frame like objects,
both in memory and out of memory.
Imports:
stringr
Depends:
R (>= 2.15.1)
License: MIT
```
---
# Current state
1. `dplyr` replaced `plyr` to specialize on data frames.
2. Current version - 0.8.1.9000.
3. https://github.com/tidyverse/dplyr
4. Developed by __Hadley Wickham__, Romain François, Lionel Henry, Kirill Müller.
5. 6000+ commits by 176 contributors.
---
background-image: url(https://www.rstudio.com/wp-content/uploads/2015/01/dplyr-hexbin-logo.png)
background-size: 100px
background-position: 90% 8%
# dplyr
5 verbs:
* `mutate()` adds new variables that are functions of existing variables
* `select()` picks variables based on their names.
* `filter()` picks cases based on their values.
* `summarise()` reduces multiple values down to a single summary.
* `arrange()` changes the ordering of the rows.
---
# Overview of the API
.pull-left[
1. Single-table verbs.
2. Single-table helpers.
3. Two-table verbs.
4. Remote tables.
5. Vector functions.
```
## [1] 236
```
]
--
.pull-right[
1. Selecting columns.
2. Transforming columns.
3. Filtering rows.
4. Summarizing and slicing.
5. `dbplyr`.
Based on https://github.com/suzanbaert/RTutorials
]
---
# Covering today
1. Breaking changes vs changing behaviour.
1. Working with names in `tidyverse`.
---
# Breaking changes
[Breaking changes](https://dbplyr.tidyverse.org/news/index.html#breaking-changes) in packages (`$`, `[[`, `[`).
```r
library("tidyverse", warn.conflicts = FALSE)
iris_db <- dbplyr::tbl_memdb(iris)
```
```
## Warning: replacing previous import 'dplyr::vars' by 'rlang::vars' when
## loading 'dbplyr'
```
```r
species <- list()
species$species <- c("setosa")
iris_db %>%
dplyr::filter(Species %in% species$species)
```
```
## Error in result_create(conn@ptr, statement): near "AS": syntax error
```
---
# Breaking changes
These will work:
```r
iris_db %>%
dplyr::filter(Species %in% !!species$species)
just_vector <- species$species
iris_db %>%
dplyr::filter(Species %in% just_vector)
iris_db %>%
filter(Species %in% local(species$species))
```
---
# Changing behaviour
```r
funx <- function(x) {
print(substitute(x))
mean(x)
}
mtcars %>%
select(1:2) %>%
summarise_all(list(~funx(.)))
```
```
## .
## .
```
```
## mpg cyl
## 1 20.09062 6.1875
```
---
# Changing behaviour
```r
# works
mtcars %>% select(1:2) %>% summarise_all(list(funx))
```
```
## mpg
## cyl
```
```
## mpg cyl
## 1 20.09062 6.1875
```
```r
mtcars %>% select(1:2) %>% summarise_all(funx)
```
```
## mpg
## cyl
```
```
## mpg cyl
## 1 20.09062 6.1875
```
```r
# doesn't
mtcars %>% select(1:2) %>% summarise_all(~funx(.))
mtcars %>% select(1:2) %>% summarise_all(list(~funx(.)))
```
---
# Working with names in `tidyverse`<sup>1</sup>
One thing is not like the other:
```r
starwars %>% mutate(birth_year - 100)
starwars %>% group_by(birth_year)
starwars %>% select(birth_year)
starwars %>% filter(birth_year < 50)
```
.footnote[
[1] Full version - https://resources.rstudio.com/rstudio-conf-2019/working-with-names-and-expressions-in-your-tidy-eval-code
]
---
Selection is special since it understands `c`, `-`, and `:` ...
```r
starwars %>% select(c(1, height))
```
--
and helpers know about variables:
```r
starwars %>% select(ends_with("color"))
```
---
However, consider following:
.pull-left[
```r
starwars %>% select(height)
```
```
## # A tibble: 87 x 1
## height
## <int>
## 1 172
## 2 167
## 3 96
## 4 202
## 5 150
## 6 178
## 7 165
## 8 97
## 9 183
## 10 182
## # … with 77 more rows
```
]
.pull-right[
```r
starwars %>% transmute(height)
```
```
## # A tibble: 87 x 1
## height
## <int>
## 1 172
## 2 167
## 3 96
## 4 202
## 5 150
## 6 178
## 7 165
## 8 97
## 9 183
## 10 182
## # … with 77 more rows
```
]
---
.pull-left[
```r
starwars %>% select(1)
```
```
## # A tibble: 87 x 1
## name
## <chr>
## 1 Luke Skywalker
## 2 C-3PO
## 3 R2-D2
## 4 Darth Vader
## 5 Leia Organa
## 6 Owen Lars
## 7 Beru Whitesun lars
## 8 R5-D4
## 9 Biggs Darklighter
## 10 Obi-Wan Kenobi
## # … with 77 more rows
```
]
.pull-right[
```r
starwars %>% transmute(1)
```
```
## # A tibble: 87 x 1
## `1`
## <dbl>
## 1 1
## 2 1
## 3 1
## 4 1
## 5 1
## 6 1
## 7 1
## 8 1
## 9 1
## 10 1
## # … with 77 more rows
```
]
---
# Passing selections
```r
starwars %>%
group_by_at(vars(ends_with("color")))
```
```
## # A tibble: 87 x 13
## # Groups: hair_color, skin_color, eye_color [67]
## name height mass hair_color skin_color eye_color birth_year gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr>
## 1 Luke… 172 77 blond fair blue 19 male
## 2 C-3PO 167 75 <NA> gold yellow 112 <NA>
## 3 R2-D2 96 32 <NA> white, bl… red 33 <NA>
## 4 Dart… 202 136 none white yellow 41.9 male
## 5 Leia… 150 49 brown light brown 19 female
## 6 Owen… 178 120 brown, gr… light blue 52 male
## 7 Beru… 165 75 brown light blue 47 female
## 8 R5-D4 97 32 <NA> white, red red NA <NA>
## 9 Bigg… 183 84 black light brown 24 male
## 10 Obi-… 182 77 auburn, w… fair blue-gray 57 male
## # … with 77 more rows, and 5 more variables: homeworld <chr>,
## # species <chr>, films <list>, vehicles <list>, starships <list>
```
---
# Writing functions with selections
```r
custom_summarize <- function(.data, ...){
.data %>%
summarize_at(vars(...), ~ mean(., na.rm = TRUE))
}
custom_summarize(starwars, height, mass)
```
```
## # A tibble: 1 x 2
## height mass
## <dbl> <dbl>
## 1 174. 97.3
```
```r
custom_summarize(starwars, starts_with("height"))
```
```
## # A tibble: 1 x 1
## height
## <dbl>
## 1 174.
```
---
# Works with groups
```r
starwars %>%
group_by(hair_color) %>%
custom_summarize(mass)
```
```
## # A tibble: 13 x 2
## hair_color mass
## <chr> <dbl>
## 1 <NA> 314.
## 2 auburn NaN
## 3 auburn, grey NaN
## 4 auburn, white 77
## 5 black 73.1
## 6 blond 80.5
## 7 blonde 55
## 8 brown 79.3
## 9 brown, grey 120
## 10 grey 75
## 11 none 78.5
## 12 unknown NaN
## 13 white 59.7
```
---
# What if we want to pass actions instead?
```r
summary_functions <- list(
~ mean(., na.rm = TRUE),
~ sd(., na.rm = TRUE)
)
summarize_acts <- function(.data, ...){
.data %>%
transmute(...) %>%
summarize_all(summary_functions)
}
summarize_acts(starwars, heightm = height / 100, bmi = mass / heightm ^ 2)
```
```
## # A tibble: 1 x 4
## heightm_mean bmi_mean heightm_sd bmi_sd
## <dbl> <dbl> <dbl> <dbl>
## 1 1.74 32.0 0.348 54.9
```
---
# Works with groups as well
```r
starwars %>%
group_by(gender) %>%
summarize_acts(heightm = height / 100, bmi = mass / heightm ^ 2)
```
```
## # A tibble: 5 x 5
## gender heightm_mean bmi_mean heightm_sd bmi_sd
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 <NA> 1.2 31.9 0.407 4.33
## 2 female 1.65 18.8 0.230 3.71
## 3 hermaphrodite 1.75 443. NA NA
## 4 male 1.79 25.7 0.354 6.49
## 5 none 2 35 NA NA
```
---
# Adding `tidyr`
```r
gather_summarize_acts <- function(.data, ...){
.data %>%
transmute(...) %>%
gather("Variable", "Value", everything()) %>%
group_by(Variable) %>%
summarize_at(vars("Value"), summary_functions)
}
starwars %>%
gather_summarize_acts(
heightm = height / 100, bmi = mass / heightm ^ 2
)
```
```
## # A tibble: 2 x 3
## Variable mean sd
## <chr> <dbl> <dbl>
## 1 bmi 32.0 54.9
## 2 heightm 1.74 0.348
```
---
# Groups don't work
```r
starwars %>%
group_by(gender) %>%
gather_summarize_acts(
heightm = height / 100,
bmi = mass / heightm ^ 2
)
```
```
## Warning in mean.default(., na.rm = TRUE): argument is not numeric or
## logical: returning NA
## Warning in mean.default(., na.rm = TRUE): argument is not numeric or
## logical: returning NA
## Warning in mean.default(., na.rm = TRUE): argument is not numeric or
## logical: returning NA
```
```
## Warning in var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm
## = na.rm): NAs introduced by coercion
```
```
## # A tibble: 3 x 3
## Variable mean sd
## <chr> <dbl> <dbl>
## 1 bmi NA 54.9
## 2 gender NA NA
## 3 heightm NA 0.348
```
---
# Use selectors
Lionel's version
```r
gather_summarize_acts <- function(.data, ...){
.data %>%
transmute(...) %>%
gather("Variable", "Value", -one_of(group_vars(.))) %>%
group_by(Variable) %>%
summarize_at(vars("Value"), summary_functions)
}
```
---
# Correct version
```r
gather_summarize_acts <- function(.data, ...){
transmute(.data, ...) %>%
gather("Variable", "Value", -one_of(group_vars(.))) %>%
group_by_at(vars(c(group_vars(.), Variable))) %>%
summarize_at(vars("Value"), summary_functions)
}
starwars %>% group_by(gender) %>%
gather_summarize_acts( heightm = height / 100, bmi = mass / heightm ^ 2)
```
```
## # A tibble: 10 x 4
## # Groups: gender [5]
## gender Variable mean sd
## <chr> <chr> <dbl> <dbl>
## 1 <NA> bmi 31.9 4.33
## 2 <NA> heightm 1.2 0.407
## 3 female bmi 18.8 3.71
## 4 female heightm 1.65 0.230
## 5 hermaphrodite bmi 443. NA
## 6 hermaphrodite heightm 1.75 NA
## 7 male bmi 25.7 6.49
## 8 male heightm 1.79 0.354
## 9 none bmi 35 NA
## 10 none heightm 2 NA
```
---
<div class="countdown blink-colon noupdate-30" id="timer_5d03540b" style="top:0;right:0;bottom:0;left:0;margin:5%;padding:20%;font-size:8em;line-height:1.25;" data-warnwhen="0">
<code class="countdown-time"><span class="countdown-digits minutes">04</span><span class="countdown-digits colon">:</span><span class="countdown-digits seconds">00</span></code>
</div>
---
# Resources
1. https://dplyr.tidyverse.org/index.html
2. http://r4ds.had.co.nz/transform.html
3. https://suzan.rbind.io/2018/01/dplyr-tutorial-1/
4. https://dplyr.tidyverse.org/reference/index.html
5. https://github.com/rstudio/cheatsheets/blob/master/data-transformation.pdf
6. https://www.nielsenmark.us/2018/07/07/connecting-r-to-postgresql-on-linux/
7. http://db.rstudio.com/
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "github",
"highlightLines": true,
"countIncrementalSlides": false
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();</script>
<script>
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</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-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html>