forked from sta523-fa20/lecture_slides
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lec_20.Rmd
813 lines (583 loc) · 13.4 KB
/
lec_20.Rmd
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
---
title: "Working with big data"
subtitle: "Programming for Statistical Science"
author: "Shawn Santo"
institute: ""
date: ""
output:
xaringan::moon_reader:
css: "slides.css"
lib_dir: libs
nature:
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
editor_options:
chunk_output_type: console
---
```{r include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
comment = "#>", highlight = TRUE,
fig.align = "center")
```
## Supplementary materials
Full video lecture available in Zoom Cloud Recordings
Additional resources
- [Chapter 2](https://adv-r.hadley.nz/names-values.html), Advanced R by Wickham, H.
- `vroom` [vignette](https://cran.r-project.org/web/packages/vroom/vignettes/vroom.html)
---
class: inverse, center, middle
# Memory basics
---
## Names and values
In R, a name has a value. It is not the value that has a name.
For example, in
```{r}
x <- c(-3, 4, 1)
```
the object named `x` is a reference to vector `c(-3, 4, 1)`.
<br/>
<center>
<img src="images/name_bind1.png">
</center>
---
We can see where this lives in memory with
```{r}
library(lobstr)
lobstr::obj_addr(x)
```
and its size with
```{r}
lobstr::obj_size(x)
```
---
## Copy-on-modify: atomic vectors
Understanding when R creates a copy of an object will allow you to write
faster code. This is also important to keep in mind when working with very
large vectors.
```{r}
x <- c(-3, 4, 1)
y <- x
```
--
```{r}
obj_addr(x)
obj_addr(y)
```
<center>
<img src="images/name_bind2.png">
</center>
---
```{r}
y[3] <- 100
```
--
```{r}
obj_addr(x)
obj_addr(y)
```
<center>
<img src="images/name_bind3.png">
</center>
---
.pull-left[
```{r}
x <- c(0, 1, 9)
y <- x
obj_addr(x)
obj_addr(y)
```
```{r}
y[4] <- -100
obj_addr(x)
obj_addr(y)
```
]
.pull-right[
<br/>
<center>
<img src="images/name_bind4.png">
</center>
<br/><br/>
<center>
<img src="images/name_bind5.png">
</center>
]
<br/>
--
Even though only one component changed in the atomic vector `y`, R created
a new object as seen by the new address in memory.
???
## Copy-on-modify and loops
Poor loop implementation
.tiny[
```{r eval=FALSE}
n <- 8
x <- 1
for (i in seq_len(n)) {
cat("Object address start iteration", i, ":", obj_addr(x), "\n")
x <- c(x, sqrt(x[i] * i))
cat("Object address end iteration ", i, ":", obj_addr(x), "\n\n")
}
```
]
"Efficient" loop implementation
.tiny[
```{r eval=FALSE}
n <- 8
x <- rep(1, n + 1)
ref(x)
for (i in seq_len(n)) {
cat("Object address start iteration", i, ":", ref(x), "\n")
x[i + 1] <- mean(x[i] * i)
cat("Object address end iteration ", i, ":", ref(x), "\n\n")
}
```
]
---
## Memory tracking
Function `tracemem()` marks an object so that a message is printed whenever the
internal code copies the object. Let's see when `x` gets copied.
<br/><br/>
```{r}
x <- c(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)
tracemem(x)
```
--
```{r}
y <- x
```
--
```{r}
y[1] <- 0
```
---
```{r}
x
y
c(obj_addr(x), obj_addr(y))
```
--
```{r}
x[1] <- 0
```
--
```{r}
lobstr::ref(x)
lobstr::ref(y)
untracemem(x)
```
---
## Copy-on-modify: lists
```{r}
x <- list(a = 1, b = 2, c = 3)
obj_addr(x)
```
--
```{r}
y <- x
```
--
```{r}
c(obj_addr(x), obj_addr(y))
```
--
```{r}
ref(x, y)
```
---
```{r}
y$c <- 4
```
--
```{r}
ref(x, y)
```
---
```{r}
x <- list(a = 1, b = 2, c = 3)
y <- x
```
--
```{r}
c(obj_addr(x), obj_addr(y))
```
--
```{r}
y$d <- 9
ref(x, y)
```
<br/>
R creates a shallow copy. Shared components exist with elements `a`, `b`, and
`c`.
---
## Copy-on-modify: data frames
```{r}
library(tidyverse)
x <- tibble(a = 1:3, b = 9:7)
```
--
```{r}
ref(x)
```
--
```{r}
y <- x %>%
mutate(b = b ^ 2)
```
--
```{r}
ref(x, y)
```
---
```{r}
z <- x
ref(x, z)
```
--
```{r}
z <- x %>%
add_row(a = -1, b = -1)
```
--
```{r}
ref(x, z)
```
--
<br/>
If you modify a column, only that column needs to be copied in memory. However,
if you modify a row, the entire data frame is copied in memory.
---
## Exercise
Can you diagnose what is going on below?
```{r}
x <- 1:10; y <- x;
tracemem(x)
c(obj_addr(x), obj_addr(y))
y[1] <- 3
```
---
## Object size
Object sizes can sometimes be deceiving.
```{r}
x <- rnorm(1e6)
y <- 1:1e6
z <- seq(1, 1e6, by = 1)
s <- (1:1e6) / 2
```
--
```{r}
c(obj_size(x), obj_size(y), obj_size(z), obj_size(s))
```
---
```{r}
c(obj_size(c(1L)), obj_size(c(1.0)))
```
--
```{r}
c(obj_size(c(1L, 2L)), obj_size(as.numeric(c(1.0, 2.0))))
```
--
```{r}
c(obj_size(c(1L, 2L, 3L)), obj_size(as.numeric(c(1.0, 2.0, 3.0))))
```
--
```{r}
c(obj_size(integer(10000)), obj_size(numeric(10000)))
```
<br/>
--
There is overhead with creating vectors in R. Take a look at `?Memory` if
you want to dig deeper as to the overhead cost.
---
## Exercise
Starting from 0 we can see that
```{r}
lobstr::obj_size(integer(0))
lobstr::obj_size(numeric(0))
```
are both 48 bytes. Based on the results on the next slide can you deduce how
R handles these numeric data in memory?
---
```{r}
diff(sapply(0:100, function(x) lobstr::obj_size(integer(x))))
```
```{r}
c(obj_size(integer(20)), obj_size(integer(22)))
```
```{r}
diff(sapply(0:100, function(x) lobstr::obj_size(numeric(x))))
```
```{r}
c(obj_size(numeric(10)), obj_size(numeric(14)))
```
---
class: inverse, center, middle
# I/O big data
---
## Getting big data into R
Dimensions: 3,185,906 x 9
```{r}
url <- "http://www2.stat.duke.edu/~sms185/data/bike/cbs_2015.csv"
```
.tiny[
```{r eval=FALSE}
system.time({x <- read.csv(url)})
```
```{r eval=FALSE}
user system elapsed
*29.739 1.085 37.321
```
]
--
.tiny[
```{r eval=FALSE}
system.time({x <- readr::read_csv(url)})
```
```{r eval=FALSE}
Parsed with column specification:
cols(
Duration = col_double(),
`Start date` = col_datetime(format = ""),
`End date` = col_datetime(format = ""),
`Start station number` = col_double(),
`Start station` = col_character(),
`End station number` = col_double(),
`End station` = col_character(),
`Bike number` = col_character(),
`Member type` = col_character()
)
|================================| 100% 369 MB
user system elapsed
*12.773 1.727 22.327
```
]
---
.tiny[
```{r eval=FALSE}
system.time({x <- data.table::fread(url)})
```
```{r eval=FALSE}
trying URL 'http://www2.stat.duke.edu/~sms185/data/bike/cbs_2015.csv'
Content type 'text/csv' length 387899567 bytes (369.9 MB)
==================================================
downloaded 369.9 MB
user system elapsed
* 7.363 2.009 19.942
```
]
--
.tiny[
```{r eval=FALSE}
system.time({x <- vroom::vroom(url)})
```
```{r eval=FALSE}
Observations: 3,185,906
Variables: 9
chr [4]: Start station, End station, Bike number, Member type
dbl [3]: Duration, Start station number, End station number
dttm [2]: Start date, End date
Call `spec()` for a copy-pastable column specification
Specify the column types with `col_types` to quiet this message
user system elapsed
* 5.873 2.361 18.606
```
]
---
## Getting bigger data into R
Dimensions: 10,277,677 x 9
```{r}
url <- "http://www2.stat.duke.edu/~sms185/data/bike/full.csv"
```
.tiny[
```{r eval=FALSE}
system.time({x <- read.csv(url)})
```
```{r eval=FALSE}
user system elapsed
*119.472 5.037 139.214
```
]
--
.tiny[
```{r eval=FALSE}
system.time({x <- readr::read_csv(url)})
```
```{r eval=FALSE}
Parsed with column specification:
cols(
Duration = col_double(),
`Start date` = col_datetime(format = ""),
`End date` = col_datetime(format = ""),
`Start station number` = col_double(),
`Start station` = col_character(),
`End station number` = col_double(),
`End station` = col_character(),
`Bike number` = col_character(),
`Member type` = col_character()
)
|================================| 100% 1191 MB
user system elapsed
*46.845 7.607 87.425
```
]
---
.tiny[
```{r eval=FALSE}
system.time({x <- data.table::fread(url)})
```
```{r eval=FALSE}
trying URL 'http://www2.stat.duke.edu/~sms185/data/bike/full.csv'
Content type 'text/csv' length 1249306730 bytes (1191.4 MB)
==================================================
downloaded 1191.4 MB
|--------------------------------------------------|
|==================================================|
user system elapsed
*33.402 7.249 79.806
```
]
--
.tiny[
```{r eval=FALSE}
system.time({x <- vroom::vroom(url)})
```
```{r eval=FALSE}
Observations: 10,277,677
Variables: 9
chr [4]: Start station, End station, Bike number, Member type
dbl [3]: Duration, Start station number, End station number
dttm [2]: Start date, End date
Call `spec()` for a copy-pastable column specification
Specify the column types with `col_types` to quiet this message
user system elapsed
*18.837 6.731 57.203
```
]
---
## Summary
| Function | Elapsed Time (s) |
|----------------------:|:------------:|
| `vroom::vroom()` | ~57 |
| `data.table::fread()` | ~80 |
| `readr::read_csv()` | ~87 |
| `read.csv()` | ~139 |
<br/>
.small[
Observations: 10,277,677
Variables: 9
]
---
class: inverse, center, middle
# Wrangling big data
---
## Package `dtplyr`
`dtplyr` provides a `data.table` backend for `dplyr`. The goal of `dtplyr` is
to allow you to write dplyr code that is automatically translated to the
equivalent, but usually much faster, `data.table` code.
<br/>
```{r}
library(dtplyr)
library(tidyverse)
```
<br/>
Since it is a backend, you will use `dplyr` verbs (functions) as before.
---
## Get big data
.tiny[
```{r eval=FALSE}
base_url <- "https://s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2019-"
month_ext <- str_pad(1:12, width = 2, pad = "0")
urls <- str_c(base_url, month_ext, ".csv", sep = "")
taxi_2019 <- map_df(urls, vroom)
```
]
*Caution:* this full dataset is a dataframe of 84,399,019 x 18.
.tiny[
```{r eval=FALSE}
# A tibble: 84,399,019 x 18
VendorID tpep_pickup_dat… tpep_dropoff_da… passenger_count trip_distance RatecodeID
<int> <chr> <chr> <int> <dbl> <int>
1 1 2019-01-01 00:4… 2019-01-01 00:5… 1 1.5 1
2 1 2019-01-01 00:5… 2019-01-01 01:1… 1 2.6 1
3 2 2018-12-21 13:4… 2018-12-21 13:5… 3 0 1
4 2 2018-11-28 15:5… 2018-11-28 15:5… 5 0 1
5 2 2018-11-28 15:5… 2018-11-28 15:5… 5 0 2
6 2 2018-11-28 16:2… 2018-11-28 16:2… 5 0 1
7 2 2018-11-28 16:2… 2018-11-28 16:3… 5 0 2
8 1 2019-01-01 00:2… 2019-01-01 00:2… 1 1.3 1
9 1 2019-01-01 00:3… 2019-01-01 00:4… 1 3.7 1
10 1 2019-01-01 00:5… 2019-01-01 01:0… 2 2.1 1
# … with 84,399,009 more rows, and 12 more variables: store_and_fwd_flag <chr>,
# PULocationID <int>, DOLocationID <int>, payment_type <int>, fare_amount <dbl>, extra <dbl>,
# mta_tax <dbl>, tip_amount <dbl>, tolls_amount <dbl>, improvement_surcharge <dbl>,
# total_amount <dbl>, congestion_surcharge <dbl>
```
]
---
## Time comparison
Using `dplyr`
.tiny[
```{r eval=FALSE}
system.time({
taxi_2019 %>%
mutate(pickup_datetime = as_datetime(tpep_pickup_datetime),
dropoff_datetime = as_datetime(tpep_dropoff_datetime),
pickup_month = month(pickup_datetime, label = TRUE),
pickup_day = wday(pickup_datetime, label = TRUE)) %>%
group_by(pickup_month, pickup_day) %>%
summarise(mean_trip_distance = mean(trip_distance))
})
user system elapsed
*339.326 21.729 444.383
```
]
--
Using `dtplyr`
.tiny[
```{r eval=FALSE}
taxi_2019_lazy <- lazy_dt(taxi_2019) #<<
system.time({
taxi_2019_lazy %>%
mutate(pickup_datetime = as_datetime(tpep_pickup_datetime),
dropoff_datetime = as_datetime(tpep_dropoff_datetime),
pickup_month = month(pickup_datetime, label = TRUE),
pickup_day = wday(pickup_datetime, label = TRUE)) %>%
group_by(pickup_month, pickup_day) %>%
summarise(mean_trip_distance = mean(trip_distance)) %>%
as_tibble() #<<
})
user system elapsed
*384.199 47.111 530.458
```
]
---
## What's the point of this package?
The benefit comes when
1. you have many many groups (millions);
2. you are sorting;
3. you are doing joins or other merges with large data.
<br/>
`dtplyr` will always be a little slower than `data.table`. However, this
slightly worse performance may be better than learning the sytax of
`data.table`.
---
class: inverse, center, middle
# Going forward
---
## Big data strategies
1. Avoid unnecessary copies of large objects
2. Downsample - you can't exceed $2 ^ 31 - 1$ rows, columns, or components
- Downsample to visualize and use summary statistics
- Downsample to wrangle and understand
- Downsample to model
3. Get more RAM - this is not easy or even sometimes an option
4. Parallelize - this is not always an option
- Execute a chunk and pull strategy
---
## References
1. Data Table Back-End for dplyr. (2020).
https://dtplyr.tidyverse.org/index.html.
2. Read and Write Rectangular Text Data Quickly. (2020).
https://vroom.r-lib.org/
3. Wickham, H. (2019). Advanced R. https://adv-r.hadley.nz/