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:
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.
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 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.
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:
f_ptype2 gives the common type. Return an empty
container holding no types, class_money(), to mean “money
of any currency”.f_cast_to casts other vectors to your type (here,
numbers become USD).f_cast_from casts your type to others (by default with
unvecvec()).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 EURIf you write your own vec_cast() method between two
vectors of your class, it must return
vecvec_cast(x, to).
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.
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 EURWhen 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.
c(). vecvec stores
non-vecvec inputs to c() and [<- as they
are. Both packages add a c() method that casts them to
their type first (numbers to degenerate distributions, for
example).unvecvec() to leave your type. It
flattens a container to its common type, which is how numeric results
(means, positions) are returned.