Creating semantic vector types with vecvec

vecvec is a foundation for packages that need one vector to hold several related types. mixtime uses it for time at different granularities (days, months, years), and distributional for distributions of different families (Normal, Poisson, …).

Both follow the same pattern:

  1. An inner type: an ordinary vector class for one variant, carrying its variant in attributes (a mixtime chronon, a distribution family). This is where the semantics live.
  2. A container: an S7 subclass of class_vecvec that stores many inner vectors side by side and behaves like a single vector.

This vignette builds a small example, a money vector holding amounts in different currencies.

library(vecvec)
library(S7)
library(vctrs)

The inner type

Each currency is an amount vector: doubles with a currency attribute. Its methods define what an amount means, e.g. you can’t add AUD to EUR.

new_amount <- function(x = double(), currency = "USD") {
  structure(as.double(x), currency = currency, class = "amount")
}

format.amount <- function(x, ...) {
  paste(formatC(unclass(x), format = "f", digits = 2), attr(x, "currency"))
}

Ops.amount <- function(e1, e2) {
  cur <- unique(c(attr(e1, "currency"), attr(e2, "currency")))
  if (length(cur) > 1) {
    stop("Can't combine ", paste(cur, collapse = " and "), ".", call. = FALSE)
  }
  out <- get(.Generic)(unclass(e1), unclass(e2))
  if (.Generic %in% c("+", "-", "*", "/")) new_amount(out, cur) else out
}

Nothing here knows about vecvec. In mixtime the inner types are mt_time classes; in distributional they are vctrs_rcrds of distribution parameters.

The container

The container is an S7 class with class_vecvec as its parent, a user-facing constructor that wraps a single inner vector, and a type name for printing.

class_money <- new_class(
  "money",
  parent = class_vecvec,
  # Set automatically when defined inside a package
  package = "mypkg"
)

money <- function(x = double(), currency = "USD") {
  class_money(list(new_amount(x, currency)))
}

method(vec_ptype_full, class_money) <- function(x, ...) "money"
method(vec_ptype_abbr, class_money) <- function(x, ...) "money"

Mixed vectors are made by combining single-type vectors.

x <- c(money(c(10, 25), "AUD"), money(5, "EUR"))
x
#> <money[3]>
#> [1] 10.00 AUD 25.00 AUD 5.00 EUR

Registering with vctrs

Call vecvec_register() in your package’s .onLoad() so the subclass works with vctrs (and so with tibbles, dplyr and tidyr). Since S7 copies the parent class into your class when your package is built, mixtime also rebuilds its class here, so it always uses the installed version of vecvec.

.onLoad <- function(libname, pkgname) {
  class_money <<- S7::new_class("money", parent = vecvec::class_vecvec)
  S7::methods_register()
  vecvec::vecvec_register(
    class_money,
    f_ptype2 = vec_ptype2_money,
    f_cast_to = vec_cast_to_money
  )
}

The optional functions decide how other types combine with yours:

vec_ptype2_money <- function(x, y, ...) class_money()

vec_cast_to_money <- function(x, to, ...) {
  if (S7_inherits(x, class_money)) return(x)
  if (is.numeric(x)) return(money(x))
  stop_incompatible_cast(x, to, x_arg = "", to_arg = "")
}

vecvec_register(
  class_money,
  f_ptype2 = vec_ptype2_money,
  f_cast_to = vec_cast_to_money
)

vec_c(x, 1)
#> <money[4]>
#> [1] 10.00 AUD 25.00 AUD 5.00 EUR  1.00 USD
tibble::tibble(x)
#> # A tibble: 3 × 1
#>   x        
#>   <money>  
#> 1 10.00 AUD
#> 2 25.00 AUD
#> 3 5.00 EUR

If you write your own vec_cast() method between two vectors of your class, it must return vecvec_cast(x, to).

What comes for free

Subsetting, rep(), printing, sorting and the Ops/Math group generics are inherited from vecvec. Each operation is applied to every inner vector, so the inner type’s methods decide the result.

x * 2
#> <money[3]>
#> [1] 20.00 AUD 50.00 AUD 10.00 EUR
x > 7
#> [1]  TRUE  TRUE FALSE
x + c(money(c(1, 2), "AUD"), money(3, "EUR"))
#> <money[3]>
#> [1] 11.00 AUD 27.00 AUD 8.00 EUR
x + money(1, "AUD")
#> Error:
#> ! Can't combine EUR and AUD.

Replicated values are stored once and only the index grows, so operations on long, repetitive vectors stay cheap.

str(rep(x, 1000)@x)
#> List of 2
#>  $ : 'amount' num [1:2] 10 25
#>   ..- attr(*, "currency")= chr "AUD"
#>  $ : 'amount' num 5
#>   ..- attr(*, "currency")= chr "EUR"

Adding methods

Write each method for the inner type, then lift it to the container with vecvec_apply_fn(). The result is simplified to ptype when given, otherwise it stays a money vector. This is how mixtime defines most of its methods (e.g. method(time_round, class_mixtime) <- vecvec_apply_fn(time_round)).

currency <- function(x) UseMethod("currency")
currency.amount <- function(x) rep(attr(x, "currency"), length(x))
method(currency, class_money) <- vecvec_apply_fn(currency, ptype = character())

currency(x)
#> [1] "AUD" "AUD" "EUR"

For one-off transformations, vecvec_apply() applies a function to each inner vector directly.

vecvec_apply(x, function(a) new_amount(unclass(a) * 1.1, attr(a, "currency")))
#> <money[3]>
#> [1] 11.00 AUD 27.50 AUD 5.50 EUR

When a method takes other vector arguments that line up with x, use vecvec_mapply(). It calls .f once per group of positions that share an inner vector, so .f must be vectorised. distributional uses this to evaluate density(), cdf() and friends at per-element values.

within_budget <- function(x, limit) {
  vecvec_mapply(
    list(x, limit),
    function(amount, limit) unclass(amount) <= limit,
    ptype = logical()
  )
}
within_budget(x, c(20, 20, 10))
#> [1]  TRUE FALSE  TRUE

Tips from mixtime and distributional