# 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](https://pola.rs) 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](#speed)), and the type checker knows every column's type at every step, so a misspelled
column is reported before the query runs ([Types](#types)). Code you already wrote for data.table
keeps working on data.table itself ([Existing data.table code](#existing-datatable-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`:

```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)
```

```text
$ ry run sales.R
   region revenue orders
   <char>   <num>  <int>
1:     eu    10.5      2
2:     us    10.0      1
3:   asia     3.5      1
```

Every 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](/reference/type-system.md#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

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](/reference/from-data-table.md) maps each
data.table idiom to its DataFrame equivalent.

## Building a DataFrame

- `DataFrame(name = value, ...)` builds one from vectors. A length-one value is recycled.
- `as.DataFrame(x)` converts a list, a `data.frame` or a `data.table`, and `is.DataFrame(x)` tests
  for one.
- `DataFrame.read_csv(path)` and `DataFrame.read_parquet(path)` read a file.
  `strings_as_factors = TRUE` reads text columns as factors, and a whole-number column becomes
  `integer` when every value fits, as `fread` does. When the path is a literal naming a `.csv`
  file in the project, the checker reads the file's header and knows its columns
  ([Columns from files](#columns-from-files)).
- `DataFrame.write_csv(df, path)` and `DataFrame.write_parquet(df, path)` write one.
- `DataFrame.concat(...)` stacks DataFrames ([Stacking and distinct rows](#stacking-and-distinct-rows)).
- `DataFrame.schema(df)`, `DataFrame.columns(df)`, `DataFrame.height(df)` and
  `DataFrame.width(df)` describe it:

```r
DataFrame.schema(sales)
```

```text
       region         units         price
"character[]"   "integer[]"    "double[]"
```

### 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:

```r
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())
```

```text
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](/guide.md#strict-mode), a query that names a column of a frame whose columns
are unknown is an error.

## 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:

```r
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()
  )
```

```text
     team total strict values  rows
   <char> <num>  <num>  <int> <int>
1:      a     3     NA      1     2
2:      b     4      4      1     1
```

Inside `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.

```r
(Expr.col("price") * 2) |> Expr.alias("double")
```

```text
(col("price") * 2.0).alias("double")
```

### Text

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"`:

```r
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 = ": ")
)
```

```text
   country sweden  first     shout             label
    <char> <lgcl> <char>    <char>            <char>
1:      SE   TRUE    Ana ANA SILVA SE-114: Ana Silva
2:      NO  FALSE     bo   BO LIND    NO-20: bo lind
3:      SE   TRUE   <NA>      <NA>              <NA>
```

### 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.

```r
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")
)
```

```text
   sensor value backup filled  best  label
   <char> <num>  <num>  <num> <num> <char>
1:      a   1.5     NA    1.5   1.5    1.5
2:      b    NA      2    0.0   2.0   <NA>
3:      c    NA     NA    0.0  -1.0   <NA>
```

### 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:

```r
sales |> DataFrame.with_columns(
  previous = Expr.shift(Expr.col("units")),
  running = Expr.cum_sum(Expr.col("units"))
)
```

```text
   region units price previous running
   <char> <int> <num>    <int>   <int>
1:     eu     3   1.5       NA       3
2:     us     5   2.0        3       8
3:     eu     2   3.0        5      10
4:   asia     7   0.5        2      17
5:     us     1   4.0        7      18
```

## Verbs

| 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)`.

```r
sales |> DataFrame.with_columns(target = c(4L, 4L, 2L, 6L, 2L), channel = "region")
```

```text
   region units price target channel
   <char> <int> <num>  <int>  <char>
1:     eu     3   1.5      4      eu
2:     us     5   2.0      4      us
3:     eu     2   3.0      2      eu
4:   asia     7   0.5      6    asia
5:     us     1   4.0      2      us
```

The 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`, `group` and `n` are
  ordinary column names. A named table is an error at run time and under `ry check`.
- The verb's own options come after the columns and match only by their full name. `sort`'s
  `desc = TRUE` is read as a column, and fails because only `select` and `with_columns` take a
  vector as a column.

```r
sales |>
  DataFrame.group_by("region") |>
  GroupBy.agg(n = Expr.len(), group = Expr.sum(Expr.col("units"))) |>
  DataFrame.sort("region")
```

```text
   region     n group
   <char> <int> <int>
1:   asia     1     7
2:     eu     2     5
3:     us     2     6
```

Naming the table is the one mistake this rule catches:

```r
DataFrame.select(df = sales, "region")
```

```text
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 name
```

`DataFrame.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.

```r
sales |> DataFrame.select("region", cost = Expr.col("price") * 1.2, Expr.col("units") >= 3L)
```

```text
   region  cost  units
   <char> <num> <lgcl>
1:     eu   1.8   TRUE
2:     us   2.4   TRUE
3:     eu   3.6  FALSE
4:   asia   0.6   TRUE
5:     us   4.8  FALSE
```

Inside `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:

```r
sales |>
  DataFrame.lazy() |>
  LazyFrame.sort("units", descending = TRUE) |>
  LazyFrame.group_by("region") |>
  LazyGroupBy.agg(top_units = Expr.col("units") |> Expr.head(2L)) |>
  LazyFrame.collect()
```

```text
   region top_units
   <char>     <int>
1:   asia         7
2:     us         5
3:     us         1
4:     eu         3
5:     eu         2
```

The 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.

### Joins

`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`:

```r
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")
```

```text
      id   name score
   <int> <char> <num>
1:     1      a    20
2:    NA      b    10
3:     2      c    NA
```

```r
regions <- DataFrame(region = ["eu", "us"], manager = ["Ana", "Bo"])
DataFrame.join(sales, regions, on = "region", how = "left")
```

```text
   region units price manager
   <char> <int> <num>  <char>
1:     eu     3   1.5     Ana
2:     us     5   2.0      Bo
3:     eu     2   3.0     Ana
4:   asia     7   0.5    <NA>
5:     us     1   4.0      Bo
```

`DataFrame.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.

```r
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")
```

```text
   ticker  time  size   bid
   <char> <int> <num> <num>
1:      a     5    10   1.6
2:      b     3    20   7.0
3:      a     1    30    NA
```

### Keys

`DataFrame.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.

```r
keyed <- sales
DataFrame.set_key(keyed, "region")
DataFrame.key(keyed)
DataFrame.key(sales)
```

```text
[1] "region"
NULL
```

### 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:

```r
sales |>
  DataFrame.drop("price") |>
  DataFrame.rename(area = "region") |>
  DataFrame.with_row_index("row")
```

```text
     row   area units
   <int> <char> <int>
1:     1     eu     3
2:     2     us     5
3:     3     eu     2
4:     4   asia     7
5:     5     us     1
```

### 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:

```r
DataFrame.concat(DataFrame.head(sales, 2L), DataFrame(region = "asia"), how = "diagonal")
```

```text
   region units price
   <char> <int> <num>
1:     eu     3   1.5
2:     us     5   2.0
3:   asia    NA    NA
```

`DataFrame.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:

```r
sales |> DataFrame.unique("region", keep = "last")
```

```text
   region units price
   <char> <int> <num>
1:     eu     2   3.0
2:   asia     7   0.5
3:     us     1   4.0
```

R'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

`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:

```r
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")
)
```

```text
   region units price region_units place
   <char> <int> <num>        <int> <int>
1:     eu     3   1.5            5     1
2:     us     5   2.0            6     1
3:     eu     2   3.0            5     2
4:   asia     7   0.5            7     1
5:     us     1   4.0            6     2
```

### 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.

```r
sales |> DataFrame.pivot(on = "region", index = "units", values = "price")
```

```text
   units  asia    eu    us
   <int> <num> <num> <num>
1:     1    NA    NA     4
2:     2    NA   3.0    NA
3:     3    NA   1.5    NA
4:     5    NA    NA     2
5:     7   0.5    NA    NA
```

`DataFrame.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:

```r
sales |> DataFrame.head(2L) |> DataFrame.unpivot(on = c("units", "price"), index = "region")
```

```text
   region variable value
   <char>   <fctr> <num>
1:     eu    units   3.0
2:     us    units   5.0
3:     eu    price   1.5
4:     us    price   2.0
```

### Dates

A 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.

```r
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"))
```

```text
      id     placed        due
   <int>     <Date>     <Date>
1:     2 2024-02-03 2024-02-17
```

The 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](#text)):

```r
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")
)
```

```text
      id     placed month    renewal      shown
   <int>     <Date> <int>     <Date>     <char>
1:     1 2024-01-31     1 2024-02-29 31.01.2024
2:     2 2024-02-03     2 2024-03-03 03.02.2024
```

## 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:

```r
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)
```

```text
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.5
2:     eu     6.0
```

The 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

`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.

```r
as.data.frame(sales)
```

```text
  region units price
1     eu     3   1.5
2     us     5   2.0
3     eu     2   3.0
4   asia     7   0.5
5     us     1   4.0
```

## Types

The 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.

```r
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:

```text
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](/reference/type-system.md#tag-types).
Build it from a `List` of tags without a payload, and compare it with a tag:

```r
# typing: strict
alias 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](#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

A column that does not exist is reported on the string that names it, with the nearest column:

```r
bad <- sales |> DataFrame.select(Expr.col("prcie"))
```

```text
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:

```r
per_region <- sales |> DataFrame.group_by("region") |> GroupBy.agg(Expr.col("units"))
```

```text
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:

```r
doubled <- sales |> DataFrame.with_columns(twice = Expr.col("region") * 2)
big <- sales |> DataFrame.filter(Expr.col("region") > 1L)
```

```text
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 column
```

### 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[]}`:

#### Inline

```r
total_units <- function(sales: DataFrame{region: character, units: integer}) -> integer {
  sum(sales$units)
}
total_units(DataFrame(region = c("eu"), unit = c(1L)))
```

#### Comments

```r
#: fn(sales: DataFrame{region: character, units: integer}) -> integer
total_units <- function(sales) {
  sum(sales$units)
}
total_units(DataFrame(region = c("eu"), unit = c(1L)))
```

```text
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](/reference/type-system.md#rows) instead, which stands
for the other columns and carries them to the result:

```r
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] 3
```

A 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](/reference/type-system.md#dataframes) lists how each verb types, and what
the checker understands of the data.table bracket syntax that DataFrames also accept.

## 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](/reference/type-system.md#datatable-queries) 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.

## Speed

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](/development/design/r-runtime.md#7-the-table-type) describe the benchmark.
