DataFrames
A DataFrame is ry’s built-in table, for code where data.table is too slow or too hard to read.
Each query runs inside the Polars engine instead of as R code, which on
db-benchmark’s questions at ten million rows takes about a sixth of the time data.table does
(Speed), and the type checker knows every column’s type at every step, so a misspelled
column is reported before the query runs (Types). Code you already wrote for data.table
keeps working on data.table itself (Existing data.table code).
You query it with Polars’ verbs (select, with_columns, filter, group_by and agg, sort,
join, join_asof, concat, unique, drop, rename, unpivot and head) and column expressions written as Expr.col("x"). DataFrames need ry’s own runtime,
so run scripts that use them with ry run script.R:
sales <- DataFrame( region = ["eu", "us", "eu", "asia", "us"], units = [3L, 5L, 2L, 7L, 1L], price = [1.5, 2, 3, 0.5, 4])sales |> DataFrame.filter(Expr.col("units") > 1L) |> DataFrame.with_columns(revenue = Expr.col("units") * Expr.col("price")) |> DataFrame.group_by("region") |> GroupBy.agg( Expr.col("revenue") |> Expr.sum(), orders = Expr.len() ) |> DataFrame.sort("revenue", descending = TRUE)$ ry run sales.R region revenue orders <char> <num> <int>1: eu 10.5 22: us 10.0 13: asia 3.5 1Every function has a qualified name, such as DataFrame.filter or Expr.sum, and takes the value
it works on as its first argument, so a query reads top to bottom with R’s pipe |>. There is no
method dispatch: DataFrame.filter always means the same function.
Write columns as lists ([1.5, 2]), so the checker holds each one to a
single type with no missing values. A plain R vector such as c(1.5, 2) works too. A column read
back with sales$price is a plain R vector, because later steps such as a left join can put NA
into a column; List.from_r(sales$price) turns it back into a List and fails if it holds an NA.
Existing data.table code
Section titled “Existing data.table code”Code written for data.table runs unchanged under ry run, on data.table’s own code. A DataFrame
is the table to choose for new code; Moving from data.table maps each
data.table idiom to its DataFrame equivalent.
Building a DataFrame
Section titled “Building a DataFrame”DataFrame(name = value, ...)builds one from vectors. A length-one value is recycled.as.DataFrame(x)converts a list, adata.frameor adata.table, andis.DataFrame(x)tests for one.DataFrame.read_csv(path)andDataFrame.read_parquet(path)read a file.strings_as_factors = TRUEreads text columns as factors, and a whole-number column becomesintegerwhen every value fits, asfreaddoes. When the path is a literal naming a.csvfile in the project, the checker reads the file’s header and knows its columns (Columns from files).DataFrame.write_csv(df, path)andDataFrame.write_parquet(df, path)write one.DataFrame.concat(...)stacks DataFrames (Stacking and distinct rows).DataFrame.schema(df),DataFrame.columns(df),DataFrame.height(df)andDataFrame.width(df)describe it:
DataFrame.schema(sales) region units price"character[]" "integer[]" "double[]"Columns from files
Section titled “Columns from files”DataFrame.read_csv("data/sales.csv") types with the columns the file has, sniffed from its first
rows with the same rules as the reader, so the checker follows a query on a file from its first
step. The path is relative to the project root, and with strings_as_factors = TRUE the text
columns are factors. With a data/sales.csv of region,units,price rows, a typo is reported
before the script runs:
sales <- DataFrame.read_csv("data/sales.csv")by_region <- sales |> DataFrame.filter(Expr.col("units") > 1L) |> DataFrame.group_by("region") |> GroupBy.agg(total = Expr.col("prcie") |> Expr.sum())type-mismatch
x this frame has no column `prcie`. Did you mean `price`? --[report.R:5:27] 4 | DataFrame.group_by("region") |> 5 | GroupBy.agg(total = Expr.col("prcie") |> Expr.sum()) | ^^^^^^^The editor completes Expr.col("...") and every column string of a verb with the columns at that step,
and hovering one shows its type. A path computed at run time, or a file the project does not have,
gives a DataFrame whose columns are unknown, so nothing about them is checked. Annotate the
variable to give it its columns, as in
sales: DataFrame{region: character, units: integer, price: double} <- DataFrame.read_csv(path).
In strict mode, a query that names a column of a frame whose columns
are unknown is an error.
Expressions
Section titled “Expressions”Expr.col("units") refers to a column. Arithmetic (+, -, *, /, ^, %/%, %%), comparisons,
&, | and ! combine columns and plain R values into a new expression, so
Expr.col("units") * Expr.col("price") and Expr.col("price") > 2 are both expressions.
Expr.lit(value) makes a constant column from a single value, and a column of its own values from
a longer vector, which must have one value per row; any other length stops with an error that
gives both lengths. Expr.is_in(expr, values) tests each value for membership in values, a
vector or an expression, and is FALSE for every value, NA included, when values is NULL.
R’s %in% cannot build an expression, so Expr.col("x") %in% values stops with an error that
points to Expr.is_in.
%% and %/% give R’s values in every case, such as 1e308 %% 5 being 0 and NA %% 0 being
NaN, but a column never raises R’s “probable complete loss of accuracy in modulus” warning.
Aggregations reduce a column to one value: Expr.sum, Expr.mean, Expr.median, Expr.min,
Expr.max, Expr.first, Expr.last, Expr.std, Expr.var, Expr.count and Expr.n_unique,
which counts the distinct values with NA as one value, as length(unique(x)) does. Expr.len()
counts rows, Expr.cor(a, b) correlates two columns, Expr.is_null tests for missing values, and
Expr.if_else(test, yes, no) picks per row.
Missing values follow Polars rather than R: Expr.sum, Expr.mean, Expr.median, Expr.min,
Expr.max, Expr.std and Expr.var skip them. Pass na_rm = FALSE for R’s rule, under which
one NA makes the result NA. Expr.count counts the values that are not missing, while
Expr.len() counts every row:
scores <- DataFrame(team = c("a", "a", "b"), points = c(3, NA, 4))scores |> DataFrame.group_by("team") |> GroupBy.agg( total = Expr.col("points") |> Expr.sum(), strict = Expr.col("points") |> Expr.sum(na_rm = FALSE), values = Expr.col("points") |> Expr.count(), rows = Expr.len() ) team total strict values rows <char> <num> <num> <int> <int>1: a 3 NA 1 22: b 4 4 1 1Inside GroupBy.agg, a key column holds its group’s one key value, as a by column does in
data.table, so Expr.col("team") |> Expr.count() is 1 for every group. Count a group’s rows with
Expr.len().
An expression’s output column takes the name of the first column it reads. Rename it with
Expr.alias, or by passing it as a named argument to a verb, as revenue = ... does above. Mind
R’s precedence when you pipe into Expr.alias: |> binds tighter than *, so wrap an arithmetic
expression in parentheses first.
(Expr.col("price") * 2) |> Expr.alias("double")(col("price") * 2.0).alias("double")The text functions take a character or factor column and give NA for a missing value:
| Function | Gives |
|---|---|
Expr.str_contains(expr, pattern, literal = FALSE) |
whether the text matches pattern |
Expr.str_starts_with(expr, prefix), Expr.str_ends_with(expr, suffix) |
whether the text starts or ends with the string |
Expr.str_replace(expr, pattern, replacement, literal = FALSE) |
the text with the first match replaced; Expr.str_replace_all replaces every match |
Expr.str_slice(expr, start, length = NULL) |
length characters from position start, counting from 1, or from the end when start is negative; a negative literal length is an error |
Expr.str_to_uppercase(expr), Expr.str_to_lowercase(expr) |
the text in upper or lower case |
Expr.str_to_date(expr, format = "%Y-%m-%d") |
a Date, or NA for text that does not match format |
Expr.concat_str(..., separator = "") |
the values joined into one string per row |
A pattern is a regular expression in the syntax of Rust’s regex crate, which Polars uses: it has
no look-around or back-references, and a replacement refers to a group as $1 rather than R’s
\\1. literal = TRUE matches the pattern as plain text. The pattern, prefix, suffix and
replacement may also be expressions, which give one per row. Expr.concat_str turns numbers into
text as as.character does, and gives NA for a row where any value is missing, where paste
would write "NA":
customers <- DataFrame(name = c("Ana Silva", "bo lind", NA), code = c("SE-114", "NO-20", "SE-9"))customers |> DataFrame.select( country = Expr.str_slice(Expr.col("code"), 1L, 2L), sweden = Expr.str_starts_with(Expr.col("code"), "SE"), first = Expr.str_replace(Expr.col("name"), "^(\\w+) .*", "$1"), shout = Expr.str_to_uppercase(Expr.col("name")), label = Expr.concat_str(Expr.col("code"), Expr.col("name"), separator = ": ")) country sweden first shout label <char> <lgcl> <char> <char> <char>1: SE TRUE Ana ANA SILVA SE-114: Ana Silva2: NO FALSE bo BO LIND NO-20: bo lind3: SE TRUE <NA> <NA> <NA>Missing values and types
Section titled “Missing values and types”Expr.fill_null(expr, value) replaces each missing value with value, a plain value or an
expression, and Expr.coalesce(...) takes each row’s first value that is not missing. Both give
the common type of their values, so filling an integer column with 0.5 gives a double column and
filling a factor with a string gives a character column; a bare NA does not count. Two factors
fill by their labels and give a factor. A Date or date-time fills only from the same type, so
Expr.coalesce(Expr.col("due"), 0L) is an error.
Expr.cast(expr, type) converts a column to "logical", "integer", "double", "character",
"factor" or "Date", as R’s as.logical, as.integer and the others do: a double prints with
15 significant digits, text reads as as.numeric reads it (surrounding blanks and hexadecimal
such as "0x10" are allowed, anything else becomes NA), a factor converts to its integer codes,
and "T" or "false" become logical values. A conversion R has no meaning for, such as a logical
to a date, is an error.
readings <- DataFrame(sensor = c("a", "b", "c"), value = c(1.5, NA, NA), backup = c(NA, 2, NA))readings |> DataFrame.with_columns( filled = Expr.fill_null(Expr.col("value"), 0), best = Expr.coalesce(Expr.col("value"), Expr.col("backup"), -1), label = Expr.cast(Expr.col("value"), "character")) sensor value backup filled best label <char> <num> <num> <num> <num> <char>1: a 1.5 NA 1.5 1.5 1.52: b NA 2 0.0 2.0 <NA>3: c NA NA 0.0 -1.0 <NA>Running values
Section titled “Running values”Expr.shift(expr, n = 1L) gives the value n rows earlier, or later for a negative n, with NA
where there is none. Expr.cum_sum(expr) gives the running total of a numeric column; a missing
value stays NA and the total skips it, as in Polars, where R’s cumsum would make every later
value NA. On an integer column, every row from the first total outside the integer range on is
NA, as in R. Both read the rows in their current order, so sort first, and wrap them in Expr.over
to restart in each group:
sales |> DataFrame.with_columns( previous = Expr.shift(Expr.col("units")), running = Expr.cum_sum(Expr.col("units"))) region units price previous running <char> <int> <num> <int> <int>1: eu 3 1.5 NA 32: us 5 2.0 3 83: eu 2 3.0 5 104: asia 7 0.5 2 175: us 1 4.0 7 18| Verb | What it does |
|---|---|
DataFrame.select(df, ...) |
keeps only the columns or expressions given |
DataFrame.with_columns(df, ...) |
adds or replaces columns, keeping the rest |
DataFrame.filter(df, ...) |
keeps the rows where every condition, an expression or a logical vector, is TRUE |
DataFrame.group_by(df, ...) then GroupBy.agg(groups, ...) |
one row per group, with one aggregation per column |
DataFrame.sort(df, ..., descending = FALSE) |
orders the rows |
DataFrame.head(df, n = 5) and DataFrame.tail(df, n = 5) |
the first or last rows |
DataFrame.join(df, other, on, how = "inner") |
joins two DataFrames |
DataFrame.join_asof(df, other, on, by = NULL) |
joins each row to the nearest row of other |
DataFrame.concat(..., how = "vertical") |
stacks DataFrames |
DataFrame.unique(df, subset = NULL, keep = "first") |
keeps one row of each set of equal rows |
DataFrame.drop(df, ...) |
removes the columns named |
DataFrame.rename(df, new = "old", ...) |
renames columns, keeping their place |
DataFrame.with_row_index(df, name = "index", offset = 1L) |
puts the row numbers first |
DataFrame.unpivot(df, on = NULL, index = NULL) |
stacks columns into rows |
A string names a column wherever a verb takes an expression, so DataFrame.select(df, "region")
is short for DataFrame.select(df, Expr.col("region")). select and with_columns also take a
named R vector with one value per row, or one value to recycle, as a column; only a single string
names a column, so channel = "region" below copies the region column. filter also takes a
logical vector with one value per row, such as DataFrame.filter(sales, sales$price > 2).
sales |> DataFrame.with_columns(target = c(4L, 4L, 2L, 6L, 2L), channel = "region") region units price target channel <char> <int> <num> <int> <char>1: eu 3 1.5 4 eu2: us 5 2.0 4 us3: eu 2 3.0 2 eu4: asia 7 0.5 6 asia5: us 1 4.0 2 usThe verbs that take columns through ... (select, with_columns, filter, group_by, agg,
sort and Expr.over) read their arguments by one rule:
- The table (or the groups, or the expression for
Expr.over) is the first positional argument. - Every named argument in a column position names a column, so
df,d,groupandnare ordinary column names. A named table is an error at run time and underry check. - The verb’s own options come after the columns and match only by their full name.
sort’sdesc = TRUEis read as a column, and fails because onlyselectandwith_columnstake a vector as a column.
sales |> DataFrame.group_by("region") |> GroupBy.agg(n = Expr.len(), group = Expr.sum(Expr.col("units"))) |> DataFrame.sort("region") region n group <char> <int> <int>1: asia 1 72: eu 2 53: us 2 6Naming the table is the one mistake this rule catches:
DataFrame.select(df = sales, "region")x `df` is read as a column, not as the table: a named argument here is a column, which must be `Expr | logical[] | integer[] | double[] | character[] | factor | Date | POSIXct`. Pass the table first, without a nameDataFrame.join, DataFrame.join_asof, head and tail take no columns through ..., so
on, how, left_on, right_on, suffix, by and n match as ordinary R arguments, prefixes
included: DataFrame.join(left, right, on = "id", ho = "left") is a left join.
Inside GroupBy.agg, each expression must
give one value per group. Expr.col("units") alone gives one value per row, so the checker and the
runtime both reject it until you aggregate it.
sales |> DataFrame.select("region", cost = Expr.col("price") * 1.2, Expr.col("units") >= 3L) region cost units <char> <num> <lgcl>1: eu 1.8 TRUE2: us 2.4 TRUE3: eu 3.6 FALSE4: asia 0.6 TRUE5: us 4.8 FALSEInside GroupBy.agg, the one exception to one value per group is Expr.head(n), which keeps up
to n values per group. Polars would give a list per group here, but ry has no list columns, so
the values become rows. After a descending sort, this gives each group’s largest values:
sales |> DataFrame.lazy() |> LazyFrame.sort("units", descending = TRUE) |> LazyFrame.group_by("region") |> LazyGroupBy.agg(top_units = Expr.col("units") |> Expr.head(2L)) |> LazyFrame.collect() region top_units <char> <int>1: asia 72: us 53: us 14: eu 35: eu 2The groups come in the order of their first row in the sorted data. Written lazily, with one
sort column and Expr.head(n) as the only item for an n of at most 8, the sort and the grouping
run as one step that keeps only each group’s best rows, instead of sorting the whole table first.
sort puts missing values last in both directions, with NaN counted as missing, so NA and
NaN rows keep their input order among themselves. Rows with equal keys keep their input order
too, descending included, and strings compare by their bytes ("B" < "_" < "a" < "é"), whatever
the locale.
DataFrame.join takes the key columns as on, or as left_on and right_on when the names
differ. how is "inner", "left", "full", "semi", "anti" or "cross", which pairs every
left row with every right row and takes no keys. The result has the left
columns, then the right’s non-key columns, and a right column whose name is already taken gets the
suffix ("_right" by default), as in Polars.
An integer key matches a double key by value, two factor keys match by label whatever their levels, and two date-time keys match by instant whatever their time zones, the result keeping the left key’s zone.
A missing key matches a missing key in every kind of join, as in R’s merge() and data.table,
where Polars would match it to nothing. A left join therefore gives a row whose key is NA the
values of a right row whose key is NA:
left <- DataFrame(id = c(1L, NA, 2L), name = ["a", "b", "c"])right <- DataFrame(id = c(NA, 1L), score = c(10, 20))DataFrame.join(left, right, on = "id", how = "left") id name score <int> <char> <num>1: 1 a 202: NA b 103: 2 c NAregions <- DataFrame(region = ["eu", "us"], manager = ["Ana", "Bo"])DataFrame.join(sales, regions, on = "region", how = "left") region units price manager <char> <int> <num> <char>1: eu 3 1.5 Ana2: us 5 2.0 Bo3: eu 2 3.0 Ana4: asia 7 0.5 <NA>5: us 1 4.0 BoDataFrame.join_asof matches each left row to one right row: the by columns must be equal, and
the on column takes the nearest value. With the default strategy = "backward" that is the last
right row at or before the left row’s value. "forward" takes the first one at or after it, and
"nearest" the closest. A left row with no match gets NA, and the columns are laid out as for a
left join.
trades <- DataFrame(ticker = ["a", "b", "a"], time = [5L, 3L, 1L], size = [10, 20, 30])quotes <- DataFrame(ticker = ["a", "a", "b"], time = [2L, 4L, 1L], bid = [1.5, 1.6, 7])DataFrame.join_asof(trades, quotes, on = "time", by = "ticker") ticker time size bid <char> <int> <num> <num>1: a 5 10 1.62: b 3 20 7.03: a 1 30 NADataFrame.set_key(df, cols) sorts df by the columns cols names and records them as its key,
and x[y] with no on joins on the key of x. It rebinds the variable it is given, so a reference
taken earlier keeps the old order and no key. DataFrame.key(df) gives the key, or NULL, and
DataFrame.copy(df) gives an independent copy.
keyed <- salesDataFrame.set_key(keyed, "region")DataFrame.key(keyed)DataFrame.key(sales)[1] "region"NULLDropping, renaming and numbering columns
Section titled “Dropping, renaming and numbering columns”DataFrame.drop(df, ...) removes the columns its strings name and keeps the rest in order.
DataFrame.rename(df, new = "old", ...) gives each named column a new name in place, the new name
first as in dplyr::rename. DataFrame.with_row_index(df, name = "index", offset = 1L) puts a
column of row numbers first, counting from 1 as R does, where Polars counts from 0. Each one stops
with an error on a column the frame does not have, and the checker reports it first:
sales |> DataFrame.drop("price") |> DataFrame.rename(area = "region") |> DataFrame.with_row_index("row") row area units <int> <char> <int>1: 1 eu 32: 2 us 53: 3 eu 24: 4 asia 75: 5 us 1Stacking and distinct rows
Section titled “Stacking and distinct rows”DataFrame.concat(...) takes DataFrames, or one list of them. With the default
how = "vertical", it stacks their rows and matches columns by name, so every frame must have the
same columns, in any order. A column takes the widest type of its pieces among logical, integer,
double and character, and a date or date-time column stacks only with its own kind.
how = "diagonal" keeps every column of any frame and fills NA where a frame lacks one, and
how = "horizontal" puts the columns of frames of the same height side by side, along with named
vectors:
DataFrame.concat(DataFrame.head(sales, 2L), DataFrame(region = "asia"), how = "diagonal") region units price <char> <int> <num>1: eu 3 1.52: us 5 2.03: asia NA NADataFrame.unique(df, subset = NULL, keep = "first") keeps one row of each set of rows equal in
the subset columns, or in every column when subset is NULL. keep picks the "first" or
"last" row of each set, or "none" drops every row that has a duplicate. The rows keep their
order:
sales |> DataFrame.unique("region", keep = "last") region units price <char> <int> <num>1: eu 2 3.02: asia 7 0.53: us 1 4.0R’s generics work on a DataFrame and give a DataFrame. rbind(a, ...) is
DataFrame.concat(a, ...), where a data.frame or a list becomes a DataFrame first (an unnamed
list takes a’s column names when it has one value per column) and NULL is skipped.
cbind(a, ...) is DataFrame.concat(a, ..., how = "horizontal"), where an unnamed vector takes the
name it is written as, as in base R, and a column name that appears twice is an error.
unique(df) is DataFrame.unique(df), and duplicated(df) gives a logical vector that is TRUE
for each row equal to an earlier one. Both take fromLast = TRUE to keep the last row of each set
instead, and both stop on any incomparables other than FALSE.
Windows and ranks
Section titled “Windows and ranks”Expr.over(expr, "key") computes expr within each group of the key columns and gives every row
its group’s value, so the frame keeps all of its rows. Expr.rank numbers the values from 1 in
order, breaking ties by row order and ranking NA last; wrap it in Expr.over to rank within
groups:
sales |> DataFrame.with_columns( region_units = Expr.over(Expr.sum(Expr.col("units")), "region"), place = Expr.over(Expr.rank(Expr.col("units"), descending = TRUE), "region")) region units price region_units place <char> <int> <num> <int> <int>1: eu 3 1.5 5 12: us 5 2.0 6 13: eu 2 3.0 5 24: asia 7 0.5 7 15: us 1 4.0 6 2Reshaping
Section titled “Reshaping”DataFrame.pivot(df, on, index, values, agg = NULL) turns the values of the on column into
columns, with one row per value of index, like data.table’s dcast. Rows and new columns come
out sorted. With several values for one cell, agg combines them: "sum", "mean", "min",
"max", "first", "last", "count" (the values that are not missing) or "len" (every
value, as fun.aggregate = length counts). Because the new columns depend on the data, the
checker types the result as a DataFrame without known columns.
sales |> DataFrame.pivot(on = "region", index = "units", values = "price") units asia eu us <int> <num> <num> <num>1: 1 NA NA 42: 2 NA 3.0 NA3: 3 NA 1.5 NA4: 5 NA NA 25: 7 0.5 NA NADataFrame.unpivot(df, on = NULL, index = NULL, variable_name = "variable", value_name = "value")
goes the other way, like data.table’s melt: the index columns repeat for each column of on,
the variable column names that column as a factor, and the value column holds its values. on
left out is every column not in index. The value column takes the widest type of the on
columns, and a warning says when numbers or logical values became text:
sales |> DataFrame.head(2L) |> DataFrame.unpivot(on = c("units", "price"), index = "region") region variable value <char> <fctr> <num>1: eu units 3.02: us units 5.03: eu price 1.54: us price 2.0A column of R Date values stays a date column. Adding or subtracting a number of days gives a
date, subtracting one date column from another gives the whole days between them as an integer,
and a date compares with another date, such as one from as.Date. The checker reports any other
operator on a date, such as Expr.col("placed") * 2.
A POSIXct column stays a date-time column with its time zone, to the microsecond. It works the
same way in seconds: adding a number of seconds gives a date-time, subtracting two date-times
gives the seconds between them as a double, and a date-time compares only with another date-time.
An Expr.if_else whose other branch is a date or date-time takes a bare NA branch as a missing
value of that type, so the column keeps its class.
orders <- DataFrame(id = [1L, 2L], placed = as.Date(c("2024-01-30", "2024-02-03")))shipped <- orders |> DataFrame.with_columns(due = Expr.col("placed") + 14L)shipped |> DataFrame.filter(Expr.col("due") >= as.Date("2024-02-15")) id placed due <int> <Date> <Date>1: 2 2024-02-03 2024-02-17The date functions take a Date or POSIXct column. Expr.dt_year, Expr.dt_month and
Expr.dt_day give integer parts. Expr.dt_offset_by(expr, by) moves by a calendar duration such
as "1mo", "-2y" or "3d12h", in Polars’ units (ns, us, ms, s, m, h, d, w,
mo, q, y). A Date moves only by whole days, weeks, months, quarters or years, so "12h"
on a Date is an error. The offset keeps a month’s end within the month, so January 31 plus a month is
February 29 in a leap year. Expr.dt_to_string(expr, format) formats with strftime codes, and
Expr.str_to_date parses text back (Text):
orders <- DataFrame(id = [1L, 2L], placed = as.Date(c("2024-01-31", "2024-02-03")))orders |> DataFrame.with_columns( month = Expr.dt_month(Expr.col("placed")), renewal = Expr.dt_offset_by(Expr.col("placed"), "1mo"), shown = Expr.dt_to_string(Expr.col("placed"), "%d.%m.%Y")) id placed month renewal shown <int> <Date> <int> <Date> <char>1: 1 2024-01-31 1 2024-02-29 31.01.20242: 2 2024-02-03 2 2024-03-03 03.02.2024Lazy queries
Section titled “Lazy queries”DataFrame.lazy(df) turns a DataFrame into a LazyFrame, and LazyFrame.scan_csv(path) or
LazyFrame.scan_parquet(path) starts one from a file without reading it. A LazyFrame has the
same verbs under the LazyFrame. prefix, but each verb only records a step.
LazyFrame.collect optimizes the whole plan and runs it, and LazyFrame.explain shows the plan
it would run:
plan <- sales |> DataFrame.lazy() |> LazyFrame.with_columns(revenue = Expr.col("units") * Expr.col("price")) |> LazyFrame.filter(Expr.col("region") == "eu") |> LazyFrame.select("region", "revenue")LazyFrame.explain(plan)LazyFrame.collect(plan)SELECT [col("region"), col("revenue")] WITH_COLUMNS [(col("units") * col("price")).alias("revenue")] FILTER col("region") == "eu" DATAFRAME 5 rows, 3 columns region revenue <char> <num>1: eu 4.52: eu 6.0The plan reads bottom up. The optimizer moved the filter below with_columns, so revenue is only
computed for the rows that survive. It also pushes filters and the columns a query needs into a
file scan, and a head into the scan’s row limit, so a lazy query over a large file reads only
what it uses.
Converting to R’s tables
Section titled “Converting to R’s tables”as.data.frame(df) gives a plain data.frame, and as.data.table(df) gives a data.table once
library(data.table) is attached. Both conversions keep every column’s type, factor levels and
missing values. A DataFrame is not a data.frame, so the conversion is always explicit:
is.data.frame(df) is FALSE, and passing a DataFrame where the checker expects a data.frame
is a type error.
as.data.frame(sales) region units price1 eu 3 1.52 us 5 2.03 eu 2 3.04 asia 7 0.55 us 1 4.0The checker knows every column of a DataFrame. Each verb produces a new column list, so the types
follow the data through a whole query, and a misspelled column, a join on a column that does not
exist, or a column that agg forgets to aggregate is reported before the query runs.
sales <- DataFrame(region = ["eu", "us"], units = [3L, 5L], price = [1.5, 2])summary <- sales |> DataFrame.filter(Expr.col("units") > 1L) |> DataFrame.with_columns(revenue = Expr.col("units") * Expr.col("price")) |> DataFrame.group_by("region") |> GroupBy.agg(total = Expr.col("revenue") |> Expr.sum(), orders = Expr.len())Hover on each name to see its type:
sales: DataFrame{region: character[], units: integer[], price: double[]}summary: DataFrame{region: character[], total: double[], orders: integer[]}The steps in between have types too. After DataFrame.group_by("region") the value is a
GroupBy{region: character[]; units: integer[], price: double[], revenue: double[]}, whose key
columns come before the semicolon. A LazyFrame carries its columns the same way, so a lazy query
is checked as closely as an eager one.
In the editor, completion inside Expr.col("...") or any column string of a verb offers the columns of
the DataFrame at that step, and hovering such a string shows the column’s type.
A column whose values are one of a few names can hold tags.
Build it from a List of tags without a payload, and compare it with a tag:
# typing: strictalias Holdings = DataFrame{kind: :Bond | :Cash, amount: double}holdings: Holdings <- DataFrame(kind = [:Bond, :Cash, :Bond], amount = c(100, 20, 50))bonds <- holdings |> DataFrame.filter(Expr.col("kind") == :Bond)cash <- holdings |> DataFrame.filter(Expr.is_in(Expr.col("kind"), [:Cash]))The table stores the column as the text of the tag names, so it prints as a <char> column and R
code reads it as a character[], through $, [[, lapply or .SD alike: holdings$kind is
c("Bond", "Cash", "Bond"). A character vector such as c("Bond", "Cash") cannot fill a tag
column, because nothing checks that its strings are tag names. For the same reason a right or
full join on a tag column and a text column gives a character[] key column. A tag compares with
a column through == and != only.
A query can start from a file too. DataFrame.read_csv("data/sales.csv") and
LazyFrame.scan_csv(...) with a literal path to a .csv file in the project have that file’s
columns, sniffed from its first rows (see Columns from files). A path
computed at run time gives a DataFrame whose columns are unknown, so annotate the variable with
its columns instead, as for any other value.
Mistakes in a query
Section titled “Mistakes in a query”A column that does not exist is reported on the string that names it, with the nearest column:
bad <- sales |> DataFrame.select(Expr.col("prcie"))type-mismatch
x the frame `sales` has no column `prcie`. Did you mean `price`?The same check covers the keys of a join. Inside GroupBy.agg, every expression must reduce each
group to one value:
per_region <- sales |> DataFrame.group_by("region") |> GroupBy.agg(Expr.col("units"))type-mismatch
x `units` gives one value per row, but `agg` needs one value per group. Aggregate it, for example with `Expr.sum` or `Expr.first`Columns have types, so arithmetic follows R’s rules: Expr.col("units") * Expr.col("price") is a double
column, a comparison is logical, and Expr.sum of an integer column stays integer. An
operation on a column whose type cannot take it is reported on that column, such as arithmetic or
Expr.sum on text, and so is a comparison of text with a number:
doubled <- sales |> DataFrame.with_columns(twice = Expr.col("region") * 2)big <- sales |> DataFrame.filter(Expr.col("region") > 1L)type-mismatch
x `*` needs numbers, but the column `region` is `character[]`
type-mismatch
x `>` compares `character[]` with `integer`, text with a number, which almost always means the wrong columnAnnotating a parameter
Section titled “Annotating a parameter”A DataFrame type lists its columns, like a record. A column type is always a vector, so
DataFrame{units: integer} means the same as DataFrame{units: integer[]}:
total_units <- function(sales: DataFrame{region: character, units: integer}) -> integer { sum(sales$units)}total_units(DataFrame(region = c("eu"), unit = c(1L)))#: fn(sales: DataFrame{region: character, units: integer}) -> integertotal_units <- function(sales) { sum(sales$units)}total_units(DataFrame(region = c("eu"), unit = c(1L)))type-mismatch
x expected `DataFrame{region: character[], units: integer[]}`, found `DataFrame{region: character[], unit: integer[]}`The columns must match exactly, as a record’s fields do, so a DataFrame with an extra column is not accepted either: an unexpected column is usually a misspelled one. A function that works on any table with some columns ends the type in a row instead, which stands for the other columns and carries them to the result:
ids <- DataFrame(region = c("eu", "us"), id = c(1L, 2L))add_id <- function<R>(sales: DataFrame{region: character, ..R}) -> DataFrame{region: character, id: integer, ..R} { DataFrame.join(sales, ids, on = "region")}out <- add_id(DataFrame(region = c("eu"), units = c(3L)))print(out$units)#> [1] 3A bare
DataFrame accepts any DataFrame and leaves its columns unknown, and so do LazyFrame,
GroupBy and LazyGroupBy. A DataFrame is not a data.frame, so a data.frame parameter
rejects it: convert with as.data.frame() first.
The typing reference lists how each verb types, and what the checker understands of the data.table bracket syntax that DataFrames also accept.
data.table syntax
Section titled “data.table syntax”A DataFrame also answers data.table’s df[i, j, by] queries, including :=, joins with on =,
.N and .SD, so code written for data.table keeps working. This syntax is there for
compatibility, and the editor completes its query symbols (.N, .SD, .I, .GRP, .NGRP and
.BY) inside the brackets. New code should use the verbs above, which the checker and the editor understand
better and which read in the order they run. The
typing reference lists what the checker understands
of the bracket syntax.
Unlike data.table, a DataFrame follows R’s copy-on-modify rule, so df[, y := value] leaves a copy
you took earlier unchanged. When no other variable refers to the DataFrame, the update happens in
place and costs only the column or the rows it writes.
db-benchmark’s ten group-by and five join questions, three := update loops and a keyed rolling
join, at ten million rows (db-benchmark’s 0.5 GB size) on 4 cores, take 3.6 s on DataFrames and
22.0 s on data.table using every thread, best of two runs each, with the same checksums, and
DataFrames are faster on every question. At fifty million rows the ten group-by questions take
11.8 s against 29.8 s. data.table’s own functions (fread, setkey, rbindlist,
melt and the rest) run data.table’s C code, and at ten million rows each is as fast as under
GNU R or faster (tstrsplit 3.7 s against 5.7 s, fread 2.4 s against 3.2 s). The
design notes describe the benchmark.