R Data Wrangling: data.table & Speed

Fast data wrangling, and making R code faster

Brendan Chapuis

March 3, 2027

Adapted from slides by Matthew DeHaven
Course Home Page

data.table

data.table

Is another package focused on data science.

It’s goals:

  • speed
  • brevity
  • no dependencies

In contrast to the tidyverse which is focused on readability.

Installing data.table

Again, we use renv to install data.table for any project we are using.

renv::install("data.table")

Then we can load the package,

library(data.table)

data.table objects

data.tables are a new object to replace data.frame.

Similar to tibbles, they have nicer default printing

data.frame(
  x = rnorm(200),
  y = rnorm(200)
)
              x           y
1    0.65399468 -0.95507971
2    0.98007055  0.72707485
3    0.55839876  2.44006047
4    2.16460859  1.31521647
5   -1.68713981  1.80392859
6    0.47626178 -0.80906479
7    0.03414528 -0.41570277
8    1.25701434  1.94272863
9   -0.01311341 -0.28495826
10   0.07495806  1.42398922
11   1.16031002 -0.42717793
12  -0.44322016  0.63284239
13  -0.20900888  1.18240158
14  -1.49455455 -0.39432400
15   0.37927435  1.43608735
16  -1.57656077  1.75564809
17  -0.44680349  0.16525076
18   2.43050809 -0.22331686
19  -1.29887814 -1.55480584
20  -0.57553025 -0.34694284
21  -1.98134582 -0.88141728
22   0.11322318  0.69433999
23   1.44566315 -0.35226753
24  -0.26933373  0.42826189
25  -0.79785462 -0.35059830
26   0.46727259  0.20271941
27   0.08039845  1.12671657
28   0.63441759 -0.51009315
29   1.12597005 -1.35109873
30   0.23021504  1.77513100
31  -0.73032894 -0.60247377
32   0.29769346  0.47756359
33   0.31965126  1.59921738
34   0.00744872  0.31778564
35  -0.21651570  0.27792887
36  -0.77603081 -2.05939031
37  -0.46417033  1.39936786
38   0.79935038  0.85222254
39   1.49956204  1.23059056
40   1.68923598  2.16137026
41  -0.32084072  0.24206603
42   0.20084491 -0.16635389
43  -0.22617849  1.38672772
44  -0.49512563  0.24309288
45  -1.27856533  1.11070117
46   1.00816381 -1.06302244
47   0.35481107  0.53963778
48  -0.39667337  1.26182953
49  -0.73109936 -0.80165483
50  -1.83079588  2.75348855
51   1.04308234  0.26310751
52  -1.52604835 -0.24121472
53   0.70026003  0.19619269
54   0.25363965  0.39069740
55  -1.64170570  0.81784351
56  -0.14274844 -1.46664645
57   0.31247993 -0.28552664
58  -1.04477646 -0.60899327
59  -3.04535008  0.15596284
60  -0.58227350  0.35558113
61  -1.15914025  1.08481920
62   0.93396820  0.70471142
63  -1.17927506 -0.86622785
64   0.84408412 -1.59528312
65   0.70074298  0.30462930
66  -2.90515384  0.89079069
67   0.94609367  1.59161273
68  -1.20102615 -0.81937406
69  -1.28817038  0.10539081
70  -0.23669139  0.96941975
71   0.10799303  1.35712203
72  -0.92555291 -0.30040473
73   0.43689881  1.19551745
74  -0.77795644 -1.36026168
75   0.55659528 -1.14311878
76   0.59110721  1.16007675
77   1.42127910  1.16824618
78  -0.74447674 -0.83866635
79  -1.82167143 -0.40715408
80  -1.71196304 -0.89754486
81   0.33144340  0.77602739
82  -0.78652932  0.24345705
83  -0.53474546  1.21156709
84  -1.24463475 -0.54833177
85   0.44886332 -0.07676932
86  -0.78495644 -0.64565634
87   0.72040260  0.63346943
88  -0.46022772  0.22546555
89  -0.35179471 -0.94224433
90   0.91997744 -0.21202699
91   0.59433218 -0.37762635
92  -0.45011312  1.14452934
93   2.32185116 -0.68572740
94  -0.76580640  0.03997568
95  -0.29904479  0.66373810
96   0.65831221  0.12747336
97   1.36430574  1.31462970
98  -0.75290467 -1.39509108
99   0.56998350  1.54617512
100  1.45884132  0.55919112
101  0.51251302 -1.04721571
102  1.35479067  0.80783857
103  0.29983569 -0.26349373
104 -0.26935447 -0.32609886
105  0.95518873  1.46909267
106 -0.62076643 -0.37370747
107 -0.66856935 -0.19756679
108 -1.28786454  0.54876115
109 -1.23671776 -0.03371264
110  0.73532393 -0.18350764
111 -1.51038314 -0.19036331
112 -0.15139356 -0.17729806
113  1.61748163 -0.37962701
114 -0.08853148  1.24095760
115  0.22347473 -1.24240086
116  0.69172256 -1.39263999
117 -2.42907114  0.42007544
118  0.01310345  0.52424551
119  0.25074065 -0.52472527
120  0.23025206  0.66092173
121  0.80891870  0.59467625
122  0.09030292 -0.58946839
123 -0.54331858 -0.58726137
124 -0.05022844  0.96005221
125  0.75082516 -1.13982983
126 -0.14447255  0.45368966
127 -0.37956401 -1.54975217
128  0.87367319  1.16521325
129  0.88476209 -1.02686356
130  0.81580592 -0.65754525
131  1.04688555 -0.37134999
132 -0.23784657 -1.34657983
133  0.06850089  0.12216600
134 -0.11347525 -0.09638316
135  1.03502861  0.98426676
136 -1.02749024  0.93042588
137 -1.52491646 -0.36181874
138 -0.20458159 -0.24663546
139 -0.72656076 -0.72829655
140 -0.32870214  1.22148503
141 -0.66828126  0.55321728
142  0.62379240 -0.74293595
143 -1.43966879  0.24828887
144  2.42865274  0.29755144
145  0.24223028 -2.25657810
146  1.79774868  0.03561119
147 -1.62812646 -0.75319021
148 -1.66569048 -1.30310016
149 -0.92561878  0.08308417
150  1.17071834 -0.74268451
151  0.85684426  0.48428164
152 -0.43657604 -0.01518075
153 -1.43429270  0.75132548
154 -0.96266488 -1.01300148
155 -0.12308408  0.14262845
156  1.64577510 -0.16417045
157 -0.58149477 -0.95002744
158 -0.64033903  1.68588318
159  1.43827685  0.45106853
160 -0.96039347  0.01096089
161  0.53484393 -0.48688930
162 -1.47296121 -1.90420110
163 -0.77392891 -1.05073314
164 -1.79172218 -0.07372084
165 -2.68962862 -0.22504449
166  0.82277159  1.89309906
167 -1.84963375 -0.58260205
168  0.53881017  0.61489795
169  4.22024566 -0.63100139
170  0.88976577  0.03373819
171  0.09050964  0.66056477
172  0.03284823 -1.41575340
173 -0.76638082  1.70973617
174 -1.44969625  0.36472254
175 -2.32485002 -0.87821941
176  1.18097420  0.71827872
177 -0.47214970 -0.97117090
178  0.79309264 -1.02923792
179 -1.16442116 -0.49256205
180  0.50900072  0.03553219
181  0.45800418  0.93380898
182  0.97573257  0.03460898
183 -0.75503618 -0.21714123
184 -1.61571034  1.76166589
185  1.34273764  0.29968984
186 -0.63869100 -1.03158197
187  0.19878416 -0.23258212
188 -0.58262320 -0.66563049
189 -0.30787801 -0.89248449
190  0.53545064  0.55764849
191  0.40708881 -1.07711969
192 -0.17958798 -1.50699082
193 -0.68343539  0.12971103
194  0.26463113 -0.39087148
195 -0.09577490 -1.23612642
196 -1.09478127 -0.91731682
197  0.50239440 -0.12619681
198  0.40428530 -1.85492574
199  0.85516553  1.54872511
200  0.40968737  1.01928811
data.table(
  x = rnorm(200),
  y = rnorm(200)
)
              x          y
          <num>      <num>
  1:  1.3727564  0.8195722
  2: -0.7844854  0.9200473
  3:  1.4354365 -1.4381948
  4:  1.7819034 -0.5630603
  5:  0.5684787 -0.2998916
 ---                      
196: -1.0599568  1.2677197
197:  0.4692477 -0.6068280
198:  0.3374004  0.6332364
199:  0.4501632  0.1491405
200: -1.2273095 -2.7611708

data.table square brackets

Remember, from base R, than we can subset vectors, matrices, and data.frames using [i,j].

This is true for data.table as well.

x <- data.table(a = rnorm(10), b = rnorm(10))
x[1,2]
            b
        <num>
1: -0.1994376

data.table square brackets

data.table takes square brackets a huge step further, by allowing

  • filtering in the ‘i’ place
  • new variable declaration in the ‘j’ place

We will look at each of these in turn.

data.table filtering

x <- data.table(a = c(-0.2, 0.1, 0.25, 0, -0.3), b = c(0.5, 0, -0.2, 0.1, 0.3))
x
       a     b
   <num> <num>
1: -0.20   0.5
2:  0.10   0.0
3:  0.25  -0.2
4:  0.00   0.1
5: -0.30   0.3

What if we want all the values where “a” is less than 0?

x[a < 0, ]
       a     b
   <num> <num>
1:  -0.2   0.5
2:  -0.3   0.3

data.table filtering

x
       a     b
   <num> <num>
1: -0.20   0.5
2:  0.10   0.0
3:  0.25  -0.2
4:  0.00   0.1
5: -0.30   0.3

Instead we could do all the values where “a” is less than “b”.

x[a < b, ]
       a     b
   <num> <num>
1:  -0.2   0.5
2:   0.0   0.1
3:  -0.3   0.3

data.table filtering

x
       a     b
   <num> <num>
1: -0.20   0.5
2:  0.10   0.0
3:  0.25  -0.2
4:  0.00   0.1
5: -0.30   0.3

In fact, we can drop the comma, as data.table will assume that only one item is always the filtering argument.

x[a < b]
       a     b
   <num> <num>
1:  -0.2   0.5
2:   0.0   0.1
3:  -0.3   0.3

tidyverse filtering equivalent

Here is a comparison of the data.table and tidyverse syntaxes side-by-side.

x[a < 0]
       a     b
   <num> <num>
1:  -0.2   0.5
2:  -0.3   0.3
x |>
  filter(a < 0)
# A tibble: 2 × 2
      a     b
  <dbl> <dbl>
1  -0.2   0.5
2  -0.3   0.3

Pretty similar, but data.table is shorter.

data.table column subsetting

Remember: data.frame subsetting uses “i” for rows, and “j” for columns. data.table follows this.

dt <- data.table(a = rnorm(5), b = rnorm(5), c = rnorm(5))
dt[, a]
[1] -1.3093431 -0.2660775 -1.8541139  0.1227263 -0.8305663

For two columns, pass a list:

dt[, list(a, b)]
            a           b
        <num>       <num>
1: -1.3093431  0.80684236
2: -0.2660775  0.08721784
3: -1.8541139 -0.10916270
4:  0.1227263 -1.12844149
5: -0.8305663  0.48081785

Or .(a,b) as equivalent:

dt[, .(a, b)]
            a           b
        <num>       <num>
1: -1.3093431  0.80684236
2: -0.2660775  0.08721784
3: -1.8541139 -0.10916270
4:  0.1227263 -1.12844149
5: -0.8305663  0.48081785

data.table variable declaration

What if we want to add a new column?

data.table does this using the column subsetting place, “j”.

dt <- data.table(a = rnorm(5), b = rnorm(5))
dt[, newcol := a + b]
dt
            a          b     newcol
        <num>      <num>      <num>
1:  1.3743330 -0.5408988  0.8334342
2:  1.7196476 -0.2605552  1.4590925
3: -1.1898337 -0.1703454 -1.3601791
4: -0.1183804 -0.9106673 -1.0290478
5:  0.1859473  0.2289064  0.4148537

:= is a data.table function representing “defined”.

Also called the “walrus” operator by some people.

data.table variable declaration

Would this work?

dt <- data.table(a = rnorm(5), b = rnorm(5))
dt[newcol := a + b]

No.

data.table will assume we are using the “i” place for rows.

dt[newcol := a + b]
Error in `value[[3L]]()`:
! Operator := detected in i, the first argument inside DT[...], but is only valid in the second argument, j. Most often, this happens when forgetting the first comma (e.g. DT[newvar := 5] instead of DT[ , new_var := 5]). Please double-check the syntax. Run traceback(), and debugger() to get a line number.

data.table variable editing

We can use the exact same syntax to edit current columns.

dt <- data.table(a = rnorm(5), b = rnorm(5))
dt[, a := 1:5]
dt
       a           b
   <int>       <num>
1:     1 -1.30626399
2:     2  1.90157302
3:     3 -0.19674442
4:     4 -0.86064438
5:     5 -0.02492935

data.table variable editing

Or to remove a column,

dt[, b := NULL]
dt
       a
   <int>
1:     1
2:     2
3:     3
4:     4
5:     5

data.table conditional editing

What if we want to remove values of “b” that are less than 0?

dt <- data.table(a = -2:2, b = -2:2)

We could conditionally declare values of “b” to be NA.

dt[b < 0, b := NA]
dt
       a     b
   <int> <int>
1:    -2    NA
2:    -1    NA
3:     0     0
4:     1     1
5:     2     2

In tidyverse, the equivalent is somewhat wordy:

dt |> mutate(b = if_else(b < 0, NA, b))

Summarizing with data.table

Remember in tidyverse we could write:

mtcars |> summarize(avg = mean(mpg))
       avg
1 20.09062

The equivalent in data.table is to pass a list .() to the “j” place:

dt <- as.data.table(mtcars)
dt[, .(avg = mean(mpg))]
        avg
      <num>
1: 20.09062

Note that I had to make “mtcars” a data.table first.

Summarizing with data.table

Instead, I could simply make the mean a new column.

dt[, avg := mean(mpg)]
dt
      mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb      avg
    <num> <num> <num> <num> <num> <num> <num> <num> <num> <num> <num>    <num>
 1:  21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4 20.09062
 2:  21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4 20.09062
 3:  22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1 20.09062
 4:  21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1 20.09062
 5:  18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2 20.09062
 6:  18.1     6 225.0   105  2.76 3.460 20.22     1     0     3     1 20.09062
 7:  14.3     8 360.0   245  3.21 3.570 15.84     0     0     3     4 20.09062
 8:  24.4     4 146.7    62  3.69 3.190 20.00     1     0     4     2 20.09062
 9:  22.8     4 140.8    95  3.92 3.150 22.90     1     0     4     2 20.09062
10:  19.2     6 167.6   123  3.92 3.440 18.30     1     0     4     4 20.09062
11:  17.8     6 167.6   123  3.92 3.440 18.90     1     0     4     4 20.09062
12:  16.4     8 275.8   180  3.07 4.070 17.40     0     0     3     3 20.09062
13:  17.3     8 275.8   180  3.07 3.730 17.60     0     0     3     3 20.09062
14:  15.2     8 275.8   180  3.07 3.780 18.00     0     0     3     3 20.09062
15:  10.4     8 472.0   205  2.93 5.250 17.98     0     0     3     4 20.09062
16:  10.4     8 460.0   215  3.00 5.424 17.82     0     0     3     4 20.09062
17:  14.7     8 440.0   230  3.23 5.345 17.42     0     0     3     4 20.09062
18:  32.4     4  78.7    66  4.08 2.200 19.47     1     1     4     1 20.09062
19:  30.4     4  75.7    52  4.93 1.615 18.52     1     1     4     2 20.09062
20:  33.9     4  71.1    65  4.22 1.835 19.90     1     1     4     1 20.09062
21:  21.5     4 120.1    97  3.70 2.465 20.01     1     0     3     1 20.09062
22:  15.5     8 318.0   150  2.76 3.520 16.87     0     0     3     2 20.09062
23:  15.2     8 304.0   150  3.15 3.435 17.30     0     0     3     2 20.09062
24:  13.3     8 350.0   245  3.73 3.840 15.41     0     0     3     4 20.09062
25:  19.2     8 400.0   175  3.08 3.845 17.05     0     0     3     2 20.09062
26:  27.3     4  79.0    66  4.08 1.935 18.90     1     1     4     1 20.09062
27:  26.0     4 120.3    91  4.43 2.140 16.70     0     1     5     2 20.09062
28:  30.4     4  95.1   113  3.77 1.513 16.90     1     1     5     2 20.09062
29:  15.8     8 351.0   264  4.22 3.170 14.50     0     1     5     4 20.09062
30:  19.7     6 145.0   175  3.62 2.770 15.50     0     1     5     6 20.09062
31:  15.0     8 301.0   335  3.54 3.570 14.60     0     1     5     8 20.09062
32:  21.4     4 121.0   109  4.11 2.780 18.60     1     1     4     2 20.09062
      mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb      avg
    <num> <num> <num> <num> <num> <num> <num> <num> <num> <num> <num>    <num>

data.table will spread any single value to the length of the table.

Multiple summaries

We can summarize multiple values or columns by simply adding arguments to .()

dt[, .(avg = mean(mpg), med = median(mpg), n = .N)]
        avg   med     n
      <num> <num> <int>
1: 20.09062  19.2    32

How do we do this by group?

We could use the filtering spot, “i”, and append each result

dt[cyl == 6,  .(avg = mean(mpg), med = median(mpg), n = .N)]
        avg   med     n
      <num> <num> <int>
1: 19.74286  19.7     7

or…

Summarizing by group

We can use the “hidden” third square bracket argument: by=

dt[, .(avg = mean(mpg), med = median(mpg), n = .N), by = cyl]
     cyl      avg   med     n
   <num>    <num> <num> <int>
1:     6 19.74286  19.7     7
2:     4 26.66364  26.0    11
3:     8 15.10000  15.2    14

We can pass multiple columns to by using the short list: .()

dt[, .(avg = mean(mpg), med = median(mpg), n = .N), by = .(cyl, gear)]
     cyl  gear    avg   med     n
   <num> <num>  <num> <num> <int>
1:     6     4 19.750 20.10     4
2:     4     4 26.925 25.85     8
3:     6     3 19.750 19.75     2
4:     8     3 15.050 15.20    12
5:     4     3 21.500 21.50     1
6:     4     5 28.200 28.20     2
7:     8     5 15.400 15.40     2
8:     6     5 19.700 19.70     1

data.table argument summary

dt[

i ,

j ,

by = ]

filtering rows

filtering columns, new columns, summarize

group by columns

tidyverse equivalent verbs

filter()

select(), mutate(), summarize()

groub_by()

Comparison

mtcars |>
  filter(hp > 100) |>
  group_by(cyl, gear) |>
  summarize(m = mean(mpg))
# A tibble: 7 × 3
# Groups:   cyl [3]
    cyl  gear     m
  <dbl> <dbl> <dbl>
1     4     4  21.4
2     4     5  30.4
3     6     3  19.8
4     6     4  19.8
5     6     5  19.7
6     8     3  15.0
7     8     5  15.4
dt[hp > 100, .(m = mean(mpg)), by = .(cyl, gear)]
     cyl  gear     m
   <num> <num> <num>
1:     6     4 19.75
2:     6     3 19.75
3:     8     3 15.05
4:     4     5 30.40
5:     8     5 15.40
6:     6     5 19.70
7:     4     4 21.40

data.table syntax is more concise, but harder to read.

Class Activity

Class Activity

  • Install and load data.table in a temporary workspace
  • Create a data.table with columns a and b of length 10 with random values
  • Add new column c which is the sum of a and b
  • Add a new column d which is the product of a and b when a is greater than 0

Modify by Reference

Which should I use? data.table or tidyverse?

The main answer:

  • personal preference (which syntax do you prefer?)

Second answer:

  • data.table is much faster
  • especially for large datasets

Speed comparison

A group that creates DuckDB (a fast database engine) does a regular speed comparison of different data manipulation tools across R, Python, Julia, and other languages:

Database-like ops benchmark

Takeaway:

  • data.table is much faster than dplyr for data manipulation in R

Why is data.table faster?

  1. optimized for speed
  1. Modifies “by reference”

tidyverse functions instead “copy-on-modify”.

Modify by reference vs. copy

Copy-on-modify

  • Creates a copy of the data
  • Modifies the copy
  • Returns the copy

Modify-in-place (modify “by reference”)

  • References the data
  • Modifies the original data

Avoids duplicating data, which is costly for your computer’s memory, especially with large datasets.

Modify by reference vs. copy

You may have noticed that I had to add an extra call to print data.tables after modifying them.

dt <- data.table(x = 1:2)
dt[, y := c("a", "b")]
dt
       x      y
   <int> <char>
1:     1      a
2:     2      b

This is because the line dt[, y := c("a", "b")] doesn’t return anything.

Because it edited the data in place, not by creating a copy.

Dangers of editing by reference

Modifying by reference can be dangerous if you are not careful.

dt <- data.table(a = 1:2, b = 3:4)
dt2 <- dt
dt2
       a     b
   <int> <int>
1:     1     3
2:     2     4

What happens to “dt” if we remove a column from “dt2”?

dt2[, b := NULL]
dt
       a
   <int>
1:     1
2:     2

“dt” and “dt2” reference the same underlying data.

Dangers of editing by reference

If you truly want a new copy of a data.table, use

dt2 <- copy(dt)

Converting to a data.table by reference

If you have a data.frame and want to convert it to a data.table, you can do this by reference as well.

df <- data.frame(a = 1:2, b = 3:4)
setDT(df)
df
       a     b
   <int> <int>
1:     1     3
2:     2     4

Instead, if you use as.data.table(), this will create a copy of the data.

df <- data.frame(a = 1:2, b = 3:4)
dt <- as.data.table(df)
df
  a b
1 1 3
2 2 4

Even Faster with Keys!

Keys

Keys provide some organization to your data.

This makes it much faster to later:

  • filter

  • group by

  • merge

data.table lets you add keys in a variety of ways.

data.table(x = c("a", "a", "b"), y = 1:3, key = "x")
dt <- as.data.table(df, key = "x")
setkey(dt, "x")

You can also pass a vector of keys c("x", "y") to use.

What are keys?

Keys provide an index for the data.

Think of this like a phone book.

If you wanted to look my phone number up in the phone book,

  • you would search under “C” for Chapuis

  • you would not search the entire phone book!

When we tell data.table to use some columns as a key, it presorts and indexes the data on those columns.

Merging with data.table

For data.table all types of merges are handled by one function:

dt <- data.table(x = c("a", "b", "c"), y = 1:3)
dt2 <- data.table(x = c("a", "c", "d"), z = 4:6)
merge(dt, dt2, by = "x")
Key: <x>
        x     y     z
   <char> <int> <int>
1:      a     1     4
2:      c     3     5

By default, merge() does an “inner” join (matches in both datasets).

Merging with data.table

A “left” join,

merge(dt, dt2, by = "x", all.x = TRUE)
Key: <x>
        x     y     z
   <char> <int> <int>
1:      a     1     4
2:      b     2    NA
3:      c     3     5

A “right” join,

merge(dt, dt2, by = "x", all.y = TRUE)
Key: <x>
        x     y     z
   <char> <int> <int>
1:      a     1     4
2:      c     3     5
3:      d    NA     6

Or an “outer” join

merge(dt, dt2, by = "x", all = TRUE)
Key: <x>
        x     y     z
   <char> <int> <int>
1:      a     1     4
2:      b     2    NA
3:      c     3     5
4:      d    NA     6

Non-matching column names

We can also be explicit about which columns to use from “x” and from “y”,

dt <- data.table(x = c("a", "b", "c"), y = 1:3)
dt2 <- data.table(XX = c("a", "c", "d"), z = 4:6)
merge(dt, dt2, by.x = "x", by.y = "XX")
Key: <x>
        x     y     z
   <char> <int> <int>
1:      a     1     4
2:      c     3     5

But it’s probably better to clean up your column names before hand.

data.table pivots

A package tidyfast which offers

  • dt_pivot_longer()
  • dt_pivot_wider()

to match the syntax of tidyr but with the speed of data.table.

data.table read / write functions

data.table has its own functions for reading and writing data, which are much faster than base R’s read.csv() and write.csv(), or tidyverse’s readr::read_csv() and readr::write_csv().

dt <- fread("path/to/input-file.csv")

fwrite(dt, "path/to/output-file.csv")

tidyverse or data.table?

tidyverse or data.table?

In practice, I (and many people) use a mix of both.

I personally prefer data.tables syntax for filtering, modifying columns, and summarizing.

If you really want the speed of data.table and the syntax of dplyr…

dtplyr

…there is a special package that combines the two!

dtplyr allows you to use all of the tidyverse verbs:

  • mutate()
  • filter()
  • groupby()

But behind the scenes runs everything using data.table.

A note on pipes

You can use pipes with data.table as well.

dt <- data.table(x = 1:2)
dt[, y := 3:4]
dt[, z := 5:6]
dt
       x     y     z
   <int> <int> <int>
1:     1     3     5
2:     2     4     6
dt <- data.table(x = 1:2)
dt |>
  _[, y := 3:4] |>
  _[, z := 5:6]
dt
       x     y     z
   <int> <int> <int>
1:     1     3     5
2:     2     4     6

The underscore character _ is known as a “placeholder”,

and represents the object being piped.

Placeholder for pipes

The placeholder _ is normally used to assign the result of a pipe to a specific named argument in a function.

x = c(1, 2, 3)
x |> append(4)
[1] 1 2 3 4

the append() function has two arguments: x and values.

We can use the placeholder to specify that the piped object should be passed to values instead of x.

x |> append(x = 4, values = _)
[1] 4 1 2 3

Making Code Faster

Making Code Faster

So far: data.table makes data wrangling fast.

Next: when the slow part is running the same task many times, we can use parallel processing.

We will use map() from purrr, so load it first.

library(purrr)

Parallel Processing

Parallel Processing

Sequential processing (default) is when code is run on one “core”.

G A Setup B Task 1 A--B C Task 2 B--C D Result C--D

Parallel Processing

Parallel processing splits operations over multiple “cores”.

G A Setup B Task 1 A--B C Task 2 A--C D Result B--D C--D

A Slow Function

Imagine we had some slow code that we wanted to run multiple times.

slow_cube <- function(x) {
  Sys.sleep(2)  ## Tells R to wait 2 seconds
  return(x ^ 3)
}

Aside: Measuring Code Speed in R

We will use the package tictoc to measure the time it takes to run our function.

library(tictoc)
tic()
Sys.sleep(1)
toc()
1.006 sec elapsed

If you want more systematic code profiling, you can use the profvis or microbenchmark packages.

Timing our Slow Function

Now we can see how long our slow function takes to run.

tic()
slow_cube(10)
[1] 1000
toc()
2.006 sec elapsed

Timing our Slow Function

And if we ran it multiple times…

tic()
map(1:3, slow_cube)
[[1]]
[1] 1

[[2]]
[1] 8

[[3]]
[1] 27
toc()
6.021 sec elapsed

Running in Parallel

If we have a multi-core machine, we can run this slow code in parallel!

library(furrr)
plan(multicore) ## If on Windows, use plan(multisession)

tic()
future_map(1:3, slow_cube)
[[1]]
[1] 1

[[2]]
[1] 8

[[3]]
[1] 27
toc()
2.108 sec elapsed

Running in Parallel

And this can scale up!

plan(multicore)

tic()
results <- future_map(1:10, slow_cube)
toc()
4.297 sec elapsed

furrr Package

The package we used is called furrr for future and purrr.

future is a package that allows you to run code in parallel.

Documentation:

Setting a Plan

The plan() function sets the parallel processing plan.

  • sequential runs code sequentially (the default)
  • multisession runs code in parallel using multiple R sessions
  • multicore runs code in parallel using multiple cores
    • Only works on Unix-based systems (Linux, MacOS) and not in Rstudio

We can be explicit in our plan on the number of parallel processes to create.

plan(multicore, workers = 2)

Available Cores

You can check how many cores you have available on your machine.

future::availableCores()
system 
     8 

The default plan() will use all available cores.

Often you will see people set things like:

plan(multicore, workers = availableCores() - 1)
plan(multicore, workers = availableCores() / 2)

This leaves some cores for you to do other things on your machine.

Why Parallel Processing with map()?

Remember that map() is a function that applies another function to each element of a list or vector.

This is always a parallel-izable task.

This is one reason it is good to use map() over a for loop.

  • easier to parallelize in the future

Another Example: Bootstrapping

Bootstrapping is a common econometric task that can be easily parallelized.

Let’s generate some data.

n = 1e3 ## One thousand observations
set.seed(42)
data <- tibble::tibble(
  x = rnorm(n),
  y = 4 + 3 * x + rnorm(n)
)
lm(y ~ x, data)

Call:
lm(formula = y ~ x, data = data)

Coefficients:
(Intercept)            x  
      3.995        3.010  

Bootstrap Function

To get some standard errors, let’s bootstrap the data.

bootstrap <- function(data, n_boot = 1e3) {
  boot_data <- data[sample(nrow(data), size = n_boot, replace = TRUE), ]
  m <- lm(y ~ x, data = boot_data)
  slope <- coef(m)[[2]]
  return(slope)
}

If we run it sequentially…

set.seed(42)
tic()
slopes_seq <- map_dbl(1:1e5, ~ bootstrap(data))
toc()
30.686 sec elapsed

Bootstrap in Parallel

Or we can run it in parallel!

plan(multicore)
tic()
slopes_par <- future_map_dbl(1:1e5, ~ bootstrap(data), .options = furrr_options(seed = 42L))
toc()
8.876 sec elapsed

After you run something in parallel, it’s good to set the plan back to sequential.

plan(sequential)

Plotting the Results

library(ggplot2)
tibble::tibble(true = 3, seq = slopes_seq, par = slopes_par) |>
  ggplot() +
  geom_density(aes(x = seq, fill = "seq"), alpha = 0.5) +
  geom_density(aes(x = par, fill = "par"), alpha = 0.5) +
  geom_vline(aes(xintercept = true), linetype = "dashed")

Plotting the Results

Packages that are already parallelized

A lot of speed performance from packages are from parallel processing.

library(data.table)
data.table 1.17.0 using 5 threads (see ?getDTthreads).  Latest news: r-datatable.com

This means that adding parallelization on top of data.table operations may not speed things up.

The fixest package also already parallelizes code for multiple fixed effect regressions.

So you have to be careful when paralleizing code that is already optimized.

Parallelization on OSCAR

We will run this on Brown’s OSCAR cluster in the OSCAR guest lecture on 3/15.

renv::install(c("tibble", "tictoc", "furrr"), prompt = FALSE)
library(tibble)
library(tictoc)
library(furrr)

availableCores()
n = 1e3 ## One thousand observations
set.seed(42)

data <- tibble::tibble(
  x = rnorm(n),
  y = 4 + 3 * x + rnorm(n)
)

bootstrap <- function(data, n_boot = 1e3) {
  boot_data <- data[sample(nrow(data), size = n_boot, replace = TRUE), ]
  m <- lm(y ~ x, data = boot_data)
  slope <- coef(m)[[2]]
  return(slope)
}

plan(multicore)

tic()
slopes_par <- future_map_dbl(1:1e5, ~ bootstrap(data), .options = furrr_options(seed = 42L))
toc()

plan(sequential)

tic()
slopes_par <- future_map_dbl(1:1e5, ~ bootstrap(data), .options = furrr_options(seed = 42L))
toc()

Live Coding Example

Live Coding Example

Speed Comparison:

library(data.table)
library(dplyr)
library(tictoc)

nrows <- 1e7 # 10 million rows

dt <- data.table(
  id    = sample(letters, nrows, replace = TRUE),
  group = sample(1:100, nrows, replace = TRUE),
  value = rnorm(nrows)
)

tb <- tibble(
  id    = dt$id,
  group = dt$group,
  value = dt$value
)

tic("data.table")
dt[group == 1, value := 0]
toc()

tic("dplyr")
tb <- tb |> mutate(value = if_else(group == 1, 0, value))
toc()

dt2 <- copy(dt)
setkey(dt2, "group")

tic("data.table grouped")
dt2[group == 1, value := 0]
toc()