data.table & SpeedFast data wrangling, and making R code faster
March 3, 2027
Adapted from slides by Matthew DeHaven
Course Home Page
data.tabledata.tableIs another package focused on data science.
It’s goals:
In contrast to the tidyverse which is focused on readability.
data.tableAgain, we use renv to install data.table for any project we are using.
data.table objectsdata.tables are a new object to replace data.frame.
Similar to tibbles, they have nicer default printing
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
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 bracketsRemember, from base R, than we can subset vectors, matrices, and data.frames using [i,j].
data.table square bracketsdata.table takes square brackets a huge step further, by allowing
We will look at each of these in turn.
data.table filtering 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?
data.table filteringInstead we could do all the values where “a” is less than “b”.
data.table filteringIn fact, we can drop the comma, as data.table will assume that only one item is always the filtering argument.
tidyverse filtering equivalentHere is a comparison of the data.table and tidyverse syntaxes side-by-side.
Pretty similar, but data.table is shorter.
data.table column subsettingRemember: data.frame subsetting uses “i” for rows, and “j” for columns. data.table follows this.
For two columns, pass a list:
data.table variable declarationWhat if we want to add a new column?
data.table does this using the column subsetting place, “j”.
:= is a data.table function representing “defined”.
Also called the “walrus” operator by some people.
data.table variable declarationWould this work?
No.
data.table will assume we are using the “i” place for rows.
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 editingWe can use the exact same syntax to edit current columns.
data.table variable editingOr to remove a column,
data.table conditional editingWhat if we want to remove values of “b” that are less than 0?
We could conditionally declare values of “b” to be NA.
data.tableRemember in tidyverse we could write:
The equivalent in data.table is to pass a list .() to the “j” place:
Note that I had to make “mtcars” a data.table first.
data.tableInstead, I could simply make the mean a new column.
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.
We can summarize multiple values or columns by simply adding arguments to .()
How do we do this by group?
We could use the filtering spot, “i”, and append each result
or…
We can use the “hidden” third square bracket argument: by=
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: .()
data.table argument summarydt[
i ,
j ,
by = ]
filtering rows
filtering columns, new columns, summarize
group by columns
tidyverse equivalent verbs
filter()
select(), mutate(), summarize()
groub_by()
data.table syntax is more concise, but harder to read.
data.table in a temporary workspacedata.table with columns a and b of length 10 with random valuesc which is the sum of a and bd which is the product of a and b when a is greater than 0data.table or tidyverse?The main answer:
Second answer:
data.table is much fasterA 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:
Takeaway:
data.table is much faster than dplyr for data manipulation in Rdata.table faster?tidyverse functions instead “copy-on-modify”.
Copy-on-modify
Modify-in-place (modify “by reference”)
Avoids duplicating data, which is costly for your computer’s memory, especially with large datasets.
You may have noticed that I had to add an extra call to print data.tables after modifying them.
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.
Modifying by reference can be dangerous if you are not careful.
What happens to “dt” if we remove a column from “dt2”?
“dt” and “dt2” reference the same underlying data.
If you truly want a new copy of a data.table, use
data.table by referenceIf you have a data.frame and want to convert it to a data.table, you can do this by reference as well.
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.
You can also pass a vector of keys c("x", "y") to use.
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.
data.tableFor data.table all types of merges are handled by one function:
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).
data.tableA “left” join,
Or an “outer” join
We can also be explicit about which columns to use from “x” and from “y”,
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 pivotsA 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 functionsdata.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().
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.
You can use pipes with data.table as well.
The underscore character _ is known as a “placeholder”,
and represents the object being piped.
The placeholder _ is normally used to assign the result of a pipe to a specific named argument in a function.
the append() function has two arguments: x and values.
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.
Sequential processing (default) is when code is run on one “core”.
Parallel processing splits operations over multiple “cores”.
Imagine we had some slow code that we wanted to run multiple times.
We will use the package tictoc to measure the time it takes to run our function.
If you want more systematic code profiling, you can use the profvis or microbenchmark packages.
Now we can see how long our slow function takes to run.
And if we ran it multiple times…
If we have a multi-core machine, we can run this slow code in parallel!
And this can scale up!
furrr PackageThe package we used is called furrr for future and purrr.
future is a package that allows you to run code in parallel.
Documentation:
The plan() function sets the parallel processing plan.
sequential runs code sequentially (the default)multisession runs code in parallel using multiple R sessionsmulticore runs code in parallel using multiple cores
You can check how many cores you have available on your machine.
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.
Bootstrapping is a common econometric task that can be easily parallelized.
Let’s generate some data.
To get some standard errors, let’s bootstrap the data.
Or we can run it in parallel!
8.876 sec elapsed

A lot of speed performance from packages are from parallel processing.
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.
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()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()