Skip to main content

14  Copies and large tables

14.1 Copies

A table shares the vectors of a data frame or a list that it is made from, and an operation on columns shares them too. An operation on rows makes new columns.

A data.table changes its columns in place, so a table takes copies of them. as.data.table() of a table copies them again, and the data.table it gives is its own:

dt <- data.table::data.table(a = c(1, 2))
r <- Raven(dt)
data.table::set(dt, 1L, "a", -1)
out <- data.table::as.data.table(r)
data.table::set(out, 1L, "a", -1)
r$a
[1] 1 2

A table is not a data frame, and set() and setnames() refuse it. setDT() of a table takes its type from it in place, after which R8 refuses the object. Two calls change a table’s vectors without R8: setDT(df) and set() on the data frame that a table was made from, and set() straight on what as.data.frame() gave. r8validate() checks a table again.

To hold a data.table as it is, by reference and unchecked, declare the field option(host_class("data.table")); r8validate(dt, type) checks it where the code asks (Structs).

14.2 DuckDB

DuckDB queries the columns of a table in place, without a copy:

r <- Raven(sex = factor(c("f", "m", "f")), age = c(40, 52, 61))
con <- DBI::dbConnect(duckdb::duckdb(shared_home = FALSE))
duckdb::duckdb_register(con, "cases", as.data.frame(r))
DBI::dbGetQuery(con, "select sex, avg(age) as age from cases group by sex order by sex")
  sex  age
1   f 50.5
2   m 52.0
DBI::dbDisconnect(con)

14.3 Time

Operations on tables run in Rust over R’s vectors. Filters of 107 rows that keep one column of doubles, against R’s condition with which(), in ms (the shortest of five runs, one session on an arm64 Mac, 2026-11-25):

Rule R8 R
x > 0.5 && y < 0.3 12 41
x > mean(x) 28 45
i > 50 && x > 0.999, of an integer column 12 25
s %in% c("a", "dd") && x > 0.999, of strings 16 118
f == "a" && x > 0.999, of a factor 12 26
d >= "2020-03-01" && x > 0.999, of dates 15 24
nchar(s) == 2 && x > 0.999 103 93

A rule is evaluated by column, over blocks of 1,024 rows. A comparison of strings with constants is made once for each text, and one of a factor once for each level. The check of a rule on two columns takes 1 ms for 106 rows, with the construction of the table. sum() in a rule is exact, so that it does not depend on the order of the rows.

A choice of rows and columns together, x[rule, columns], copies only the columns asked for. r8select() before r8filter() does the same.

© 2026 E.D. Gennatas