Skip to main content

3  Structs

A struct is a type whose values hold every one of its fields. new_struct() declares one. GBM holds the settings of a gradient boosting machine:

GBM <- new_struct(
  "GBM",
  description = "Settings of a gradient boosting machine.",
  fields = list(
    n_trees = field(
      type_integer(min = 1L),
      default = 500L,
      description = "Number of trees."
    ),
    learning_rate = field(
      type_double(exclusive_min = 0, max = 1),
      default = 0.1,
      description = "Contribution of each tree."
    ),
    loss = type_character(values = c("squared", "absolute", "huber")),
    seed = option(type_integer(min = 0L))
  )
)

3.1 Values

The struct is its own constructor. A field with a default may be omitted, and so may an option() field, which is then NULL:

gbm <- GBM(loss = "huber", learning_rate = 0.05)
gbm
<demo::GBM>
  n_trees: 500
  learning_rate: 0.05
  loss: "huber"
  seed: NULL

3.2 Copies

A value shares its vectors with the code around it, and regular R values, which are vectors, matrices, factors, and data frames, are not copied. Construction, reading a field, replacing another field, validation, comparison, hashing, dispatch, and saving to a file take the vector where it is. What a read gives, such as x$values, is a view of the value’s vector: R’s functions read it in place, and copy it before they change it, as they do any shared vector. Rust code reads the same memory.

R8 makes a new vector in three cases. The field’s type asks for other elements: an integer vector for a double field, a factor with other levels, or a date-time below a microsecond. The vector is of at most 128 bytes, where a copy takes no more than a view. Or it is a column of a data.table.

3.2.1 data.table

R8 does not need data.table, and a table field takes a data frame, a tibble, or a data.table.

data.table changes its columns in place. R8 therefore copies the columns of a data.table that a constructor takes, and stores a data frame. What a read gives is safe to turn into one: as.data.table(x$tab) and setDT() copy the columns, so that := and set() on the result leave the value as it is.

Fold <- new_struct("Fold", fields = list(
  metrics = type_table(columns = list(rmse = column(type_double(min = 0))))
))
fold <- Fold(metrics = data.frame(rmse = runif(100)))
m <- fold$metrics
data.table::setDT(m)
data.table::set(m, 1L, "rmse", -1)
min(fold$metrics$rmse) >= 0
[1] TRUE

Three uses of data.table reach a vector that a value shares, since nothing marks it: V(v = DT$a) and then DT[1, a := -1], where copy(DT$a) gives the value a vector of its own; W(tab = df) and then setDT(df) and :=; and set() on a data frame that a read gave. r8validate(x) checks a value again, and is the call to make after code that changes a data.table in place.

A large table that data.table manipulates is held as it is, by reference, in a field of host_class("data.table"), or passed as an argument. R8 does not check its content: that field is the exception to “a value is valid”. r8validate() requires that an object satisfies a type where the code needs it, with one pass over the data:

Cases <- type_table(
  columns = list(age = column(type_double(min = 0))),
  open = TRUE
)
Dataset <- new_struct("Dataset", fields = list(
  data = option(host_class("data.table")),
  target = type_character()
))
d <- Dataset(
  data = data.table::data.table(age = c(40, 52), y = c(0, 1)),
  target = "y"
)
r8validate(d$data, Cases)

3.3 Validation

The constructor checks every field against its declaration. An error lists every problem, with the requirement, the value found, and the nearest allowed value:

GBM(n_trees = 0L, learning_rate = 2, loss = "hubber")
Error:
! Invalid `demo::GBM`: 3 problems
- `n_trees` must be at least 1; found 0. [below_min]
- `learning_rate` must be at most 1; found 2. [above_max]
- `loss` must be one of "squared", "absolute", or "huber"; found "hubber"; the nearest value is "huber". [not_in_values]

A value of another accepted form converts to the field’s type. Here the double 200 becomes the integer 200L:

GBM(n_trees = 200, loss = "squared")$n_trees
[1] 200

3.4 Reading and replacing fields

$ and [[ read a field by its exact name:

gbm$learning_rate
[1] 0.05
gbm[["loss"]]
[1] "huber"
gbm$rate
Error:
! `rate` is not a field of `demo::GBM`. Fields: n_trees, learning_rate, loss, seed.

A field has no position. gbm[[1]] is an error that names the field at that position, and as.list() gives a list to go through:

gbm[[1]]
Error:
! A field is read by name; field 1 is `n_trees`: gbm[["n_trees"]]; names(gbm) gives the field names.

[ reads several fields as a list, and as.list() all of them, so a value is an argument of lapply() and vapply():

str(gbm[c("n_trees", "loss")])
List of 2
 $ n_trees: int 500
 $ loss   : chr "huber"
vapply(gbm, class, "")
      n_trees learning_rate          loss          seed 
    "integer"     "numeric"   "character"        "NULL" 

inherits() tests for a value of a type:

inherits(gbm, GBM)
[1] TRUE

A value does not change. $<- returns a new value with the field replaced and checked:

slow <- gbm
slow$learning_rate <- 0.01
c(gbm$learning_rate, slow$learning_rate)
[1] 0.05 0.01
slow$learning_rate <- 0
Error:
! Invalid `demo::GBM` from `x$learning_rate <- value`: 1 problem
- `learning_rate` must be above 0; found 0. [below_min]

[<- replaces several fields, from a list with one value per field:

tuned <- list(n_trees = 1000L, learning_rate = 0.01)
gbm[names(tuned)] <- tuned
gbm
<demo::GBM>
  n_trees: 1000
  learning_rate: 0.01
  loss: "huber"
  seed: NULL

3.5 Field types

Declaration Holds
type_logical(), type_integer(), type_double(), type_character() One value
type_date(), type_posixct() One date, or one date-time
vec(type) A vector of any length
type_factor() A factor
type_matrix(), type_array(), type_sparse_matrix() A matrix, an array, or a sparse matrix
type_table() A data frame with declared columns
btree_map(type), index_map(type) Values by name, sorted by name or in the order given
type_raw(), type_json() Bytes, or any JSON value
option(type) A value of the type, or NULL
An R8 type, such as GBM A value of that type
subtype(Struct) A value of a struct or of one that extends it (Extending a struct)
dyn(Trait) A value of any type that implements a trait (Traits and impls)
option(host_class(class)) An object of another class system (Methods for R classes)

A type takes the constraints of its values:

Type Constraints
type_integer() min, max, exclusive_min, exclusive_max, values
type_double() min, max, exclusive_min, exclusive_max, values, infinite, nan
type_character() pattern, values
type_factor() levels, ordered
vec() min_length, max_length, unique, and the constraints of its element type

Each side of a range takes an inclusive or an exclusive bound. A requirement that involves several fields is a rule.

A double is a finite number unless its type says otherwise. infinite = TRUE admits the infinities that the bounds leave, and nan = TRUE admits NaN, the result of a calculation that is undefined, which is in no range. A missing value, NA, is option()’s, as for every type:

Declaration Values
type_double(min = 0) 0 and above
type_double(min = 0, infinite = TRUE) 0 and above, or Inf
type_double(min = 0, max = 1, nan = TRUE) 0 to 1, or NaN
vec(option(type_double(nan = TRUE))) numbers, NaN, and NA

A calculation on a field is R’s and has no type. Its result is checked where it enters a field, a column, an argument, or a result that declares one:

Scores <- new_struct("Scores", fields = list(log_odds = vec(type_double())))
Scores(log_odds = log(c(0.2, -1, 3)))
Warning in log(c(0.2, -1, 3)): NaNs produced
Error:
! Invalid `demo::Scores`: 1 problem
- `log_odds[[2]]` must be a number; found NaN. 1 of 3 elements is NaN. Where a calculation may give no number, `nan = TRUE` in the type admits NaN. [nan_value]

field(type, default, description) adds a default and a description to a type.

3.6 Tables

type_table() declares the columns of a data frame. column() adds what holds for a column as a whole, such as distinct values:

Trial <- new_struct(
  "Trial",
  fields = list(
    doses = type_table(list(
      patient = column(type_character(), unique = TRUE),
      dose_mg = type_double(min = 0)
    ))
  )
)
Trial(doses = data.frame(patient = c("P1", "P1"), dose_mg = c(50, -10)))
Error:
! Invalid `demo::Trial`: 2 problems
- `doses$patient[[2]]`: "P1" appears more than once. [not_unique]
- `doses$dose_mg[[2]]` must be at least 0; found -10. [below_min]

3.7 Fields filled later

A field may depend on others, or on data that is not at hand when the value is built. compute gives an expression over the other fields, and context = TRUE marks a field that the caller supplies. Both are option() fields, which r8resolve() fills:

RandomForest <- new_struct(
  "RandomForest",
  fields = list(
    n_features = type_integer(min = 1L),
    mtry = field(
      option(type_integer(min = 1L)),
      compute = calc(floor(n_features / 3)),
      description = "Features tried at each split."
    ),
    n_cores = field(option(type_integer(min = 1L)), context = TRUE)
  )
)
forest <- RandomForest(n_features = 30L)
r8resolve(forest, context = list(n_cores = 4L))
<demo::RandomForest>
  n_features: 30
  mtry: 10
  n_cores: 4

A field that the value already holds keeps its value.

© 2026 E.D. Gennatas