forked from stulacy/speeding-up-R-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slides.qmd
1900 lines (1481 loc) · 56.7 KB
/
slides.qmd
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
---
title: "Speeding up R"
date: "2023-06-28"
author: "Stuart Lacy"
execute:
cache: true
keep-md: true
format:
revealjs:
smaller: false
slide-number: c/t
show-slide-number: all
scrollable: true
theme: default
navigation-mode: linear
width: 1280
height: 700
embed-resources: true
---
## Introduction
- Focus on techniques for speeding up analysis of tabular data
- Subjects:
- Vectorization
- Joins
- `Rcpp`
- `data.table`
- Alternative backends
```{r setup, echo=F}
library(tidyverse)
library(knitr)
library(kableExtra)
options(dplyr.summarise.inform = FALSE)
```
```{r pprint}
pprint <- function(df, n=NULL, font_size=14) {
df_name <- as.character(match.call())[2]
if (is.null(n)) {
n <- nrow(df)
}
df |>
head(n) |>
kable(format="html",
caption=sprintf("%s: Rows 1 - %d out of %d",
df_name, n, nrow(df)),
escape=TRUE) |>
kable_styling(font_size=font_size)
}
```
# Vectorization
## Vectorization Concept
> For loops in R are slow - many StackOverflow posts
- In general, if you're using a `for` loop (or a `sapply` variant), then your code could be sped up by using a `vectorised` function
- Definition: `f(x[i]) = f(x)[i]` for $i \in 1, ..., N$
. . .
- `sqrt(c(4, 9, 16)) = 2, 3, 4`, therefore `sqrt` is vectorised
- Using vectorised functions often results in **cleaner code** with less chance for bugs
- There are a lot of vectorised functions available in the standard library
## Standard library vectorised functions {.smaller}
```{r df-creation, echo=FALSE}
df <- data.frame(x=runif(10, min=3, max=8), y=rnorm(10), z=sin(1:10), xy="")
df$z[c(3, 8)] <- NA
```
:::: {.columns}
::: {.column width="50%"}
- Non-vectorised
```r
for (i in 1:nrow(df)) {
# New column based on 2 others
if (df$x[i] > 5 && df$y[i] < 0) {
df$y[i] <- 5
} else {
df$y[i] <- 0
}
# Replace NAs with error code
if (is.na(df$z[i])) {
df$z[i] <- 9999
}
# String concatenate columns
df$xy[i] <- paste(df$x[i], df$y[i], sep="_")
}
# Distance between every row
dists <- matrix(nrow=nrow(df), ncol=nrow(df))
for (i in 1:nrow(df)) {
for (j in 1:nrow(df)) {
if (j != i) {
dists[i, j] <- sqrt((df$x[i] - df$x[j])**2 + (df$y[i] - df$y[j])**2)
}
}
}
```
:::
::: {.column width="50%"}
- Vectorised
```r
# New column based on 2 others
df$y <- ifelse(df$x > 5 & df$y < 0, 5, 0)
# Replace NAs with error code
df$z[is.na(df$z)] <- 9999
# Concatenate columns
df$xy <- paste(df$x, df$y, sep="_")
# Distance between every row
dist(df[, c('x', 'y')])
```
:::
::::
## Worked example
- Example taken from [Jim Hester's blog post](https://www.jimhester.com/post/2018-04-12-vectorize/)
> Given a path some/path/abc/001.txt, create a fast function to return abc_001.txt
. . .
- First attempt works on a single path at a time, separating it by `/` and concatenating the last directory and filename
- Doesn't work for a vector input, is there an easy way to vectorise it?
```{r string-1, echo=TRUE}
example_1 <- function(path) {
path_list <- str_split(path, "/") %>% unlist()
paste(path_list[length(path_list) - 1], path_list[length(path_list)], sep = "_")
}
example_1(c("foo/bar/car/001.txt", "har/far/lar/002.txt"))
```
## Version 1 - `Vectorize`
- `Vectorize` takes a function that works on a single element, and returns a vectorised version - job done!
. . .
- However, it just uses `apply` under the hood and **isn't quicker**, mostly just syntatical sugar
```{r string-1-vec, echo=TRUE}
example_1_vectorised <- Vectorize(example_1) # This returns a *function*
example_1_vectorised(c("foo/bar/car/001.txt", "har/far/lar/002.txt"))
```
## Version 2
- Want to replace this implicit for loop with inbuilt vectorised functions
- ✅ `str_split` is vectorised, returning a list over the input entries
- ✅ `paste` is also vectorised
- ❌ Need to use a for loop (`sapply`) to grab the last dir and filename from each entry
- Overall have reduced the computation done inside the for loop
```{r string-2, echo=TRUE}
example_2 <- function(paths) {
path_list <- str_split(paths, "/")
last_two <- sapply(path_list, tail, 2)
paste(last_two[1, ], last_two[2, ], sep="_")
}
example_2(c("foo/bar/car/001.txt", "har/far/lar/002.txt"))
```
## Version 3
- We can't directly replace this for loop with a single vectorised function, have to take another approach
- `dirname('foo/bar/dog.txt') = foo/bar`
- `basename('foo/bar/dog.txt') = dog.txt`
- Combining these can give us our entire functionality in 4 inbuilt vectorised function calls!
```{r string-3, echo=TRUE}
example_3 <- function(paths) {
paste(basename(dirname(paths)), basename(paths), sep="_")
}
example_3(c("foo/bar/car/001.txt", "har/far/lar/002.txt"))
```
## Comparison
- The `microbenchmark` library makes it easy to time snippets of code
- The `Vectorize` version isn't doing anything different from manually looping through with `sapply`
```{r string-comp, echo=TRUE}
library(microbenchmark)
# Construct 100 paths
paths <- rep(c("some/path/abc/001.txt", "another/directory/xyz/002.txt"), 100)
res <- microbenchmark(
example_1_vectorised(paths),
sapply(paths, example_1),
example_2(paths),
example_3(paths)
)
summary(res)[c("expr", "median")]
```
## Conclusions {.smaller}
> In general, if you're using a `for` loop (or a `sapply` variant), then your code could be sped up by using a `vectorised` function - Me (7 slides ago)
- This wasn't fully correct, as vectorised functions can have for loops under the hood and will thus still be slow
- The difference between a vectorised function built using `Vectorize` or an inbuilt function like `basename` is that the latter will have a for loop, **but it will be written in C/C++ rather than R**
. . .
> In general, if you're using a `for` loop (or a `sapply` variant), then your code could be sped up by using a for loop written in C/C++, preferably part of the standard library - Me (now)
- Later on will demonstrate how to write our own C++ functions
# DataFrames & Joining
## Basic DataFrame operations {.smaller}
- Fortunately working with `data.frame`s and the `tidyverse` core verbs pushes you towards using vectorised functions
- `group_by() |> summarise()` is both quicker and more legible than manually looping over the groups and combining the results
- `filter(f(x))` assumes that `f()` is vectorised and returns a boolean `TRUE/FALSE` for every row
- `mutate(newcol=f(oldcol))` assumes `f()` is vectorised and returns a value per row
. . .
- **Caution**, can run into errors or unexpected behaviour if not using vectorised functions
:::: {.columns}
::: {.column width="50%"}
```{r string-error, echo=TRUE}
# Non-vectorised version didn't Error,
# but gave an unexpected result
data.frame(path=paths) |>
mutate(path_clean1 = example_1(path),
path_clean2 = example_3(path)) |>
head()
```
:::
::: {.column width="50%"}
```{r string-ifelse, echo=TRUE, error=TRUE}
# This function isn't vectorised due to the if/else statement
# Solution: Use ifelse() instead
replace_both_NA_9999 <- function(x, y) {
if (is.na(x) && is.na(y)) {
return(9999)
} else {
return(0)
}
}
data.frame(a=c(5, 3, NA, 2, NA),
b=c(NA, 2, NA, 1, 9)) |>
mutate(c = replace_both_NA_9999(a, b))
```
:::
::::
## Joining {.smaller}
- Linking 2 datasets together using the `join` family of functions is an integral part of data analysis
- However, `join` functions are highly efficient functions and can be useful in a number of siutations, even when we don't have 2 separate datasets
- `inner_join` links two dataframes together based on a column in common, with the number of rows equal to the number of rows in the 'left' table that have a matching row in the 'right' table
```{r join-setup}
df_1 <- data.frame(group=c('a', 'b', 'c'), value1=c(1, 2, 3))
df_2 <- data.frame(group=c('b', 'c', 'd'), value2=c(4, 5, 6))
```
:::: {.columns}
::: {.column width="30%"}
```{r join-display, echo=FALSE}
pprint(df_1, font_size = 18)
```
:::
::: {.column width="30%"}
```{r join-display-2, echo=FALSE}
pprint(df_2, font_size = 18)
```
:::
::: {.column width="40%"}
```{r join-display-3, echo=TRUE}
joined <- df_1 |> inner_join(df_2, by="group")
```
```{r join-display-4}
pprint(joined, font_size = 18)
```
:::
::::
## Example usage: inner join instead of `ifelse` {.smaller}
- Can think of `inner_join` as being able to both `filter` and `mutate` new columns
- Example: apply different per-group scaling factor to 300,000 measurements from 3 groups
- On one joining column `join` isn't much quicker, but it's far more legible and scales well to both having more groups in the joining column, and additional joining columns
:::: {.columns}
::: {.column width="30%"}
```{r join-setup-2, echo=FALSE}
n_per_group <- 1e5
df <- data.frame(group=rep(c('a', 'b', 'c'), each=n_per_group),
time = rep(seq.POSIXt(from=as_datetime("2020-03-05"),
by="1 min",
length.out=n_per_group),
3),
value = rnorm(n_per_group * 3))
```
```{r join-display-5}
pprint(df, 5, font_size=15)
```
:::
::: {.column width="30%"}
```{r join-scales}
scales <- data.frame(group=c('a', 'b', 'c'),
scale=c(2, 7.8, 9))
```
```{r join-scales-2}
pprint(scales, font_size=15)
```
:::
::: {.column width="30%"}
```{r join-scales-3}
joined <- df |> inner_join(scales, by="group")
```
```{r join-scales-4}
pprint(joined, 5, font_size=15)
```
:::
::::
. . .
```{r join-scales-comp, echo=TRUE}
f_join <- function() {
df |> inner_join(scales, by="group")
}
f_ifelse <- function() {
df |>
mutate(scale = ifelse(group == 'a', 2,
ifelse(group == 'b', 7.8,
ifelse(group == 'c', 9, NA))))
}
res <- microbenchmark(f_join(), f_ifelse(), times=10)
summary(res)[c("expr", "median")]
```
## `left_join`
- A `left_join` returns **all rows** in the left table, but only those in the right that match the condition
- Any column from the right table that didn't have a match in the left table is filled with `NA`
```{r join-inner-1}
df1 <- data.frame(group=c('a', 'b', 'c', 'd'), val1 = seq(4))
df2 <- data.frame(group=c('a', 'b', 'c'), val2 = seq(3)**2)
```
:::: {.columns}
::: {.column width="15%"}
```{r join-left-1, echo=TRUE}
df1
```
:::
::: {.column width="15%"}
```{r join-left-2, echo=TRUE}
df2
```
:::
::: {.column width="35%"}
```{r join-left-3, echo=TRUE}
df1 |>
left_join(df2, by="group")
```
:::
::: {.column width="35%"}
```{r join-left-4, echo=TRUE}
df1 |>
inner_join(df2, by="group")
```
:::
::::
## Example usage: filling gaps with `left_join`
- Very useful if want to be aware of missing values
- Useful for filling gaps in non-uniformly sampled time-series so can count missingness or interpolate
:::: {.columns}
::: {.column width="30%"}
```{r join-left-5, echo=FALSE}
df <- data.frame(date=as_date(c('2020-01-01', '2020-01-03', '2020-01-05')),
measurement = rnorm(3))
```
```{r join-left-6, echo=TRUE}
df
```
:::
::: {.column width="20%"}
```{r join-left-7, echo=FALSE}
all_times <- data.frame(date = seq.Date(from=min(df$date), to=max(df$date), by=1))
```
```{r join-left-8, echo=TRUE}
all_times
```
:::
::: {.column width="50%"}
```{r join-left-9, echo=TRUE}
all_times |> left_join(df, by="date")
```
:::
::::
## Interval joins {.smaller}
- Joins aren't limited to joining on equal values, can also join on **intervals** or **closest value**
- Example: Have measurements from every day in 2020, but want to limit analysis to 5 specific weeks
```{r join-intervals-1}
df_interval <- data.frame(time = seq.Date(from=as_date("2020-01-01"), to=as_date("2020-12-31"), by=1),
measurement = rnorm(366))
weeks <- data.frame(week_group = c('a', 'b', 'c', 'd', 'e'),
week_start = as_date(c("2020-02-14", "2020-03-17", "2020-05-08", "2020-09-20", "2020-11-13")),
week_end = as_date(c("2020-02-21", "2020-03-24", "2020-05-15", "2020-09-27", "2020-11-20")))
```
:::: {.columns}
::: {.column width="20%"}
```{r join-intervals-2, echo=FALSE}
pprint(df_interval, 10, font_size=15)
```
:::
::: {.column width="25%"}
```{r join-intervals-3, echo=FALSE}
pprint(weeks, font_size=15)
```
:::
::: {.column width="50%"}
```{r join-intervals-4, echo=TRUE}
joined <- df_interval |>
inner_join(weeks,
by=join_by(time >= week_start, time < week_end))
```
```{r join-intervals-5}
pprint(joined, 10, font_size=15)
```
:::
::::
## Benchmark {.smaller}
- On only 366 rows with 5 groups it is 10x as fast, will scale better, and is more understandable
```{r join-intervals-6, echo=TRUE}
f_intervaljoin <- function() {
df_interval |>
inner_join(weeks, by=join_by(time >= week_start, time < week_end))
}
f_ifelse <- function() {
df_interval |>
mutate(week_group = ifelse(time >= as_date("2020-02-14") & time < as_date("2020-02-21"),
'a',
ifelse(time >= as_date("2020-03-17") & time < as_date("2020-03-24"),
'b',
ifelse(time >= as_date("2020-05-08") & time < as_date("2020-05-15"),
'c',
ifelse(time >= as_date("2020-09-20") & time < as_date("2020-09-27"),
'd',
ifelse(time >= as_date("2020-11-13") & time < as_date("2020-11-20"),
'e',
NA)))))) |>
filter(!is.na(week_group))
}
res <- microbenchmark(f_intervaljoin(), f_ifelse(), times=10)
summary(res)[c("expr", "median")]
```
# Different backends
## Example dataset {.smaller}
- What if we're using fast functions but still experiencing slow performance due to dataset's *size*?
- Example dataset: Company House data containing 5 million rows ([440MB archive download](http://download.companieshouse.gov.uk/en_output.html), extracts to 2.4GB) of all companies incorporated in the UK since 1856
- Using first million rows as an example
```{r company-house-1, echo=TRUE}
df <- read_csv("BasicCompanyDataAsOneFile-2023-05-01.csv", n_max=1e6, show_col_types=FALSE)
df$IncorporationDate <- as_date(df$IncorporationDate, format="%d/%m/%Y")
dim(df)
```
```{r company-house-2, echo=TRUE}
df |>
select(CompanyName, RegAddress.PostTown, IncorporationDate, SICCode.SicText_1) |>
head()
```
## Question 1: How many companies have the same name?
- Will use several basic research questions to have some 'real-world' analysis code to benchmark
- How many companies have the same name?
```{r company-house-3, echo=T}
df |>
count(CompanyName) |>
filter(n > 1) |>
nrow()
```
## Question 2: What York postcode has the most businesses?
- Want to find the 5 postcodes with most businesses being created in York
- Need to do some string manipulation to extract the first part of the `YOXX YYY` postcode format
```{r company-house-4, echo=TRUE}
df |>
filter(RegAddress.PostTown == 'YORK') |>
mutate(postcode = word(RegAddress.PostCode, 1, sep=" ")) |>
count(postcode) |>
arrange(desc(n)) |>
head(5)
```
## Question 3: Classifications {.smaller}
- Companies can be assigned with up to 4 classifications from a list of 1,042 options
- Do classifications tend to cluster together? I.e. is the average number of classifications a company has related to the first classification?
- Slightly tenuous example but wanted to demonstrate pivoting + joining!
- Only want to look at classifications that are used by at least 10 companies (`inner_join` to filter)
- Multiple classifications are stored in 4 **wide columns** that are NA when unused - easier to count the number of non-null column entries in **long** format
```{r company-house-5}
df |>
select(CompanyName, SICCode.SicText_1, SICCode.SicText_2, SICCode.SicText_3, SICCode.SicText_4) |>
head()
```
## Question 3: Classifications (code) {.smaller}
```{r company-house-8, echo=TRUE}
# 755 rows containing the SIC codes that at least 10 companies have
# Only 1 column, SICCode.SicText_1
sic_10_companies <- df |>
count(SICCode.SicText_1) |>
filter(n >= 10) |>
select(SICCode.SicText_1)
df |>
# Could do a filter to restrict to these 10 companies, but it's actually quicker to use an inner join
inner_join(sic_10_companies, by="SICCode.SicText_1") |>
select(CompanyNumber, SICCode.SicText_1, SICCode.SicText_2, SICCode.SicText_3, SICCode.SicText_4) |>
mutate(first_classification = SICCode.SicText_1) |>
# Pivoting to make it easier to count how many non-NULL classifications each company has
pivot_longer(c(SICCode.SicText_1, SICCode.SicText_2, SICCode.SicText_3, SICCode.SicText_4)) |>
filter(!is.na(value)) |>
# Count how many classifications each company has
count(CompanyNumber, first_classification) |>
# Calculate the average number per the first classification
group_by(first_classification) |>
summarise(mean_classifications = mean(n, na.rm=T)) |>
arrange(desc(mean_classifications)) |>
head()
```
# data.table
## Introduction {.smaller}
- `data.table` is an alternative to data.frame/tibble that is optimised for speed and low memory usage
- The trade-off is that its API is a bit/lot less user friendly
```{r data-table-1, echo=TRUE, message=FALSE}
library(data.table)
dt <- fread("BasicCompanyDataAsOneFile-2023-05-01.csv", nrows=1e6) # fread is the equivalent of read.csv
dt[, IncorporationDate := as_date(IncorporationDate, format="%d/%m/%Y") ] # Creates a new column by *reference*
dim(dt)
```
```{r data-table-2, echo=TRUE}
# Display rows 1-5 and the specified columns
dt[1:5, .(CompanyName, RegAddress.PostTown, IncorporationDate, SICCode.SicText_1)]
```
## Counting number of companies with the same name
- Generally, `dt[i, j, k]` means for data table `dt`, filter on rows `i`, create and/or select columns `j`, and group by `k`
- `data.table` operations don't use the Pipe (`|>` or `%>%`), so can either chain together `[]` or create intermediate variables
- `data.table` have `data.frame` as a class so can use standard functions on them, just won't benefit from the speed up
- `.N` is the equivalent of `count`
```{r data-table-3, echo=T}
nrow( dt[ , .N, by=.(CompanyName) ][ N > 1 ] )
```
## York Postcodes with most business
- In this example it's easier to create an intermediate variable than use a one-liner
- `.SD` applies an operation to a subset of columns (all by default)
```{r data-table-4, echo=TRUE}
postcodes <- dt[ RegAddress.PostTown == 'YORK', .(postcode = word(RegAddress.PostCode, 1))][, .N, by=postcode]
postcodes[order(-postcodes$N), head(.SD, 5)]
# Alternative one-liner
#setorder(dt[ RegAddress.PostTown == 'YORK', .(postcode = word(RegAddress.PostCode, 1))][, .N, by=postcode], -N)[, head(.SD, 5)]
```
## Number of classifications {.smaller}
- Joins are less intuitive. `x[y]` is equal to `left_join(y, x)`, **NOT** `inner_join(x, y)`
- `melt` is equivalent to `pivot_longer` and IMO less intuitive
- Intermdiate variables everywhere!
```{r data-table-5, echo=TRUE}
sic_10_companies_dt <- dt[, .N, by=.(SICCode.SicText_1)][ N >= 10, .(SICCode.SicText_1) ]
dt_companies_wide <- dt[ sic_10_companies_dt, # This is a join!
.(CompanyNumber,
first_classification = SICCode.SicText_1,
SICCode.SicText_1,
SICCode.SicText_2,
SICCode.SicText_3,
SICCode.SicText_4),
on=.(SICCode.SicText_1)]
dt_companies_long <- melt(dt_companies_wide, id.vars=c('CompanyNumber', 'first_classification'))
dt_companies_mean <- dt_companies_long[ value != '', # Removes the unused SIC columns
.N,
by=.(CompanyNumber, first_classification)][,
.(mean_classifications = mean(N, na.rm=T)),
by=.(first_classification)]
head(dt_companies_mean[ order(mean_classifications, decreasing = TRUE)])
```
## Speed comparison with tidyverse
```{r data-table-6}
f_read_tidyverse <- function() {
read_csv("BasicCompanyDataAsOneFile-2023-05-01.csv", n_max=1e6, show_col_types=FALSE)
}
f_read_datatable <- function() {
fread("BasicCompanyDataAsOneFile-2023-05-01.csv", nrows=1e6)
}
f_count_companies_tidyverse <- function() {
df |>
count(CompanyName) |>
filter(n > 1) |>
nrow()
}
f_count_companies_datatable <- function() {
nrow( dt[ , .N, by=.(CompanyName) ][ N > 1 ] )
}
f_postcode_tidyverse <- function() {
df |>
filter(RegAddress.PostTown == 'YORK') |>
mutate(postcode = word(RegAddress.PostCode, 1)) |>
count(postcode) |>
arrange(desc(n)) |>
head(5)
}
f_postcode_datatable <- function() {
setorder(dt[ RegAddress.PostTown == 'YORK', .(postcode = word(RegAddress.PostCode, 1))][, .N, by=postcode], -N)[, head(.SD, 5)]
}
f_postcode_datatable_2 <- function() {
postcodes <- dt[ RegAddress.PostTown == 'YORK', .(postcode = word(RegAddress.PostCode, 1))][, .N, by=postcode]
postcodes[order(-postcodes$N), head(.SD, 5)]
}
f_sic_tidyverse <- function() {
sic_10_companies <- df |>
count(SICCode.SicText_1) |>
filter(n >= 10) |>
select(SICCode.SicText_1)
df |>
select(CompanyNumber, SICCode.SicText_1, SICCode.SicText_2, SICCode.SicText_3, SICCode.SicText_4) |>
inner_join(sic_10_companies, by="SICCode.SicText_1") |>
mutate(first_classification = SICCode.SicText_1) |>
pivot_longer(c(SICCode.SicText_1, SICCode.SicText_2, SICCode.SicText_3, SICCode.SicText_4)) |>
filter(!is.na(value)) |>
count(CompanyNumber, first_classification) |>
group_by(first_classification) |>
summarise(mean_classifications = mean(n, na.rm=T)) |>
arrange(desc(mean_classifications))
}
f_sic_datatable <- function() {
sic_10_companies_dt <- dt[, .N, by=.(SICCode.SicText_1)][ N >= 10, .(SICCode.SicText_1) ]
dt_companies_wide <- dt[ sic_10_companies_dt,
.(CompanyNumber,
first_classification = SICCode.SicText_1,
SICCode.SicText_1,
SICCode.SicText_2,
SICCode.SicText_3,
SICCode.SicText_4),
on=.(SICCode.SicText_1)]
dt_companies_long <- melt(dt_companies_wide, id.vars=c('CompanyNumber', 'first_classification'))
dt_companies_mean <- dt_companies_long[ value != '', .N, by=.(CompanyNumber, first_classification)][, .(mean_classifications = mean(N, na.rm=T)), by=.(first_classification)]
dt_companies_mean[ order(mean_classifications, decreasing = TRUE)]
}
```
```{r data-table-comparison-benchmark}
res_read <- microbenchmark(f_read_tidyverse(), f_read_datatable(), times=1)
res_count <- microbenchmark(f_count_companies_tidyverse(), f_count_companies_datatable(), times=1)
res_postcode <- microbenchmark(f_postcode_tidyverse(), f_postcode_datatable(), times=3)
res_sic <- microbenchmark(f_sic_tidyverse(), f_sic_datatable(), times=3)
```
```{r data-table-comparison-results}
results <- list(
"ReadingCSV"=res_read,
"CountCompanies"=res_count,
"Postcode"=res_postcode,
"Categories"=res_sic
) |>
map(function(x) tibble(expr=x$expr, time=x$time)) |>
list_rbind(names_to="benchmark") |>
mutate(library = gsub(".+_.+_", "", expr),
library = gsub("\\(\\)", "", library)) |>
group_by(benchmark, library) |>
summarise(time = median(time)) |>
ungroup() |>
mutate(benchmark = factor(benchmark, levels=c("ReadingCSV", "CountCompanies", "Postcode", "Categories"),
labels=c("Reading CSV", "Duplicate companies", "Postcodes", "Classifications")),
time = time / 1e9)
stats <- results |>
pivot_wider(names_from="library", values_from="time") |>
mutate(reference = tidyverse) |>
pivot_longer(c(datatable, tidyverse), names_to="library") |>
mutate(speedup = reference / value,
speedup_label = sprintf("%.1fx", speedup)) |>
group_by(benchmark) |>
mutate(ypos = value) |>
ungroup()
results |>
ggplot(aes(x=library, y=time, fill=library)) +
geom_col() +
facet_wrap(~benchmark, scales="free_y") +
theme_minimal() +
scale_fill_brewer("Library", palette="Dark2") +
guides(fill="none") +
labs(y="Time (s)", x="") +
geom_text(aes(label=speedup_label, y=ypos), data=stats) +
theme(
axis.text = element_text(size=16),
legend.position = "bottom",
axis.title = element_text(size=18),
legend.text = element_text(size=16),
legend.title = element_text(size=18),
strip.text = element_text(size=18)
)
```
# `tidytable` and `dtplyr`
## `tidytable`: introduction {.smaller}
:::: {.columns}
::: {.column width="40%"}
- `tidytable` is a drop-in replacement for common tidyverse functions that under the hood work on a `data.table` object
- So (in theory!) you get the speed of `data.table` but the user friendly API of the `tidyverse`
- Just load the library then all subsequent calls to `mutate`, `inner_join`, `count`, `select`, `filter` etc... will use the `tidytable` versions that work on a `data.table`
- **Beware**: not all functions have been ported over and it explicitly overwrites the `dplyr`, `tidyr`, `purrr` functions
- There's a lag between changes to `tidyverse` being reflected in `tidytable`
:::
::: {.column width="60%"}
```{.r}
library(tidytable)
# Here we explicitly create tidytable from a regular data.frame
# But passing a regular data.frame or data.table into any tidytable function
# will implicitly change it to be a tidytable object
dtt <- as_tidytable(df)
dtt |>
count(SICCode.SicText_1) |>
filter(n >= 10) |>
select(SICCode.SicText_1)
```
```{r, echo=FALSE}
# Dodgy way of showing output from running code without having to load tidytable and wreck namespace
dtt <- tidytable::as_tidytable(df)
dtt |>
tidytable::count(SICCode.SicText_1) |>
tidytable::filter(n >= 10) |>
tidytable::select(SICCode.SicText_1)
```
```{r tidytable-1-hidden, echo=FALSE, fig.pos=""}
dtt <- tidytable::as_tidytable(df)
# NB: In interactive work would use library(tidytable)
# Being explicit here to not ruin namespace
f_count_companies_tidytable <- function() {
dtt |>
tidytable::count(CompanyName) |>
tidytable::filter(n > 1) |>
nrow()
}
f_postcode_tidytable <- function() {
dtt |>
tidytable::filter(RegAddress.PostTown == 'YORK') |>
tidytable::mutate(postcode = word(RegAddress.PostCode, 1)) |>
tidytable::count(postcode) |>
tidytable::arrange(desc(n)) |>
head(5)
}
f_sic_tidytable <- function() {
sic_10_companies <- dtt |>
tidytable::count(SICCode.SicText_1) |>
tidytable::filter(n >= 10) |>
tidytable::select(SICCode.SicText_1)
dtt |>
tidytable::select(CompanyNumber, SICCode.SicText_1, SICCode.SicText_2, SICCode.SicText_3, SICCode.SicText_4) |>
tidytable::inner_join(sic_10_companies, by="SICCode.SicText_1") |>
tidytable::mutate(first_classification = SICCode.SicText_1) |>
tidytable::pivot_longer(c(SICCode.SicText_1, SICCode.SicText_2, SICCode.SicText_3, SICCode.SicText_4)) |>
tidytable::filter(!is.na(value)) |>
tidytable::count(CompanyNumber, first_classification) |>
tidytable::group_by(first_classification) |>
tidytable::summarise(mean_classifications = mean(n, na.rm=T)) |>
tidytable::arrange(desc(mean_classifications))
}
```
:::
::::
## `dtplyr`: introduction {.smaller}
:::: {.columns}
::: {.column width="40%"}
- An alternative `data.table` wrapper is `dtplyr` (developed by RStudio team)
- Works differently to `tidytable`: it sequentially builds up the equivalent `data.table` query, but only executes the code when you **explicitly** request it (using `collect()` or `as.data.frame/table()`)
- Loading the package **doesn't** affect your environment
- Has less coverage than `tidytable`
:::
::: {.column width="60%"}
```{r dtplyr-1, echo=TRUE}
library(dtplyr)
# dtplyr operates on `lazy data.tables` which are only created by this function
dtp <- lazy_dt(df)
dtp |>
count(SICCode.SicText_1) |>
filter(n >= 10) |>
select(SICCode.SicText_1)
```
:::
::::
## `dtplyr`: usage {.smaller}
:::: {.columns}
::: {.column width="45%"}
- Can view the generated `data.table` query (subtly different to the one I manually wrote)
```{r dtplyr-2, echo=TRUE}
dtp |>
count(SICCode.SicText_1) |>
filter(n >= 10) |>
select(SICCode.SicText_1) |>
show_query()
```
:::
::: {.column width="45%"}
- Run `collect()` to execute it and return a `tibble`
```{r dtplyr-3, echo=TRUE}
dtp |>
count(SICCode.SicText_1) |>
filter(n >= 10) |>
select(SICCode.SicText_1) |>
collect() |>
head()
```