S3 vectors

This vignette shows you how to create your own S3 vector classes. It focuses on the aspects of making a vector class that every class needs to worry about; you’ll also need to provide methods that actually make the vector useful.

I assume that you’re already familiar with the basic machinery of S3, and the vocabulary I use in Advanced R: constructor, helper, and validator. If not, I recommend reading at least the first two sections of the S3 chapter of Advanced R.

library(vctrs)

This vignette works through five big topics:

They’re collectively demonstrated with a number of simple S3 classes:

Basics

In this section you’ll learn how to create a new vctrs class by calling new_vctr(). This creates an object with class vctrs_vctr which has a number of methods. These are designed to make your life as easy as possible. For example:

Percent class

In this section, I’ll show you how to make a percent class, i.e. a double vector that is printed as a percentage. We start by defining a low-level constructor that uses vec_assert() to checks types and/or sizes then calls new_vctr().

percent is built on a double vector of any length and doesn’t have any attributes.

Note that we prefix the name of the class with the name of the package. This prevents conflicting definitions between packages.

We then follow up with a user friendly helper. Here we’ll use vec_cast() to allow it to accept anything coercible to a double:

Before you go on, check that user-friendly constructor returns a zero-length vector when called with no arguments. This makes it easy to use as a prototype.

format() method

The first method for every class should almost always be a format() method. This should return a character vector the same length as x. The easiest way to do this is to rely on one of R’s low-level formatting functions like formatC():

(Note the use of vec_data() so format() doesn’t get stuck in an infinite loop, and that I take a little care to not convert NA to "NA"; this leads to better printing.)

The format method is also used by data frames, tibbles, and str():

For optimal display, I recommend also defining an abbreviated type name, which should be 4-5 letters for commonly used vectors. This is used in tibbles and in str():

If you need more control over printing in tibbles, implement a method for pillar::pillar_shaft(). See https://tibble.tidyverse.org/articles/extending.html for details.

Casting and coercion

The next set of methods you are likely to need are those related to coercion and casting. Coercion and casting are two sides of the same coin: changing the prototype of an existing object. When the change happens implicitly (e.g in c()) we call it coercion; when the change happens explicitly (e.g. with as.integer(x)), we call it casting.

One of the main goals of vctrs is to put coercion and casting on a robust theoretical footing so it’s possible to make accurate predictions about what (e.g.) c(x, y) should do when x and y have different prototypes. vctrs achieves this goal through two generics:

Double dispatch

Both generics use double dispatch which means that the implementation is selected based on the class of two arguments, not just one. S3 does not natively support double dispatch, but we can implement with a trick: doing single dispatch twice. In practice, this means you end up with method names with two classes, like vec_type2.foo.bar(), and you need a little boilerplate to get started. The key idea that makes double dispatch work without any modifications to S3 is that a function (like vec_type2.foo()) can be both an S3 generic and an S3 method.

We’ll discuss what this boilerplate does in the upcoming sections; just remember you’ll always need to copy and paste it when creating a new S3 class.

Percent class

We’ll make our percent class coercible back and forth with double vectors. I’ll start with the boilerplate for vec_type2():

The default method provides a user friendly error message if the coercion doesn’t exist. The vctrs_unspecified is needed to handle NA, which is technically a logical vector, but we want to stand in for a missing value of any type.

Next, start by saying that a vctrs_percent combined with a vctrs_percent yields a vctrs_percent, which we indicate by returning a prototype generated by the constructor.

Next we define methods that say that combining a percent and double should yield a percent. Because double dispatch is a bit of a hack, we need to provide two methods. It’s your responsibility to ensure that each pair return the same result: if they don’t you will get weird and unpredictable behaviour.

We can check that we’ve implemented this correctly with vec_ptype():

Next we implement explicit casting, again starting with the boilerplate:

Then providing a method to coerce a percent to a percent:

And then for converting back and forth between doubles. To convert a double to a percent we use the percent() helper (not the constructor; this is unvalidated user input). To convert a percent to a double, we strip the attributes.

Then we can check this works with vec_cast():

Once you’ve implemented vec_type2() and vec_cast() you get vec_c() and [<- implementations for free.

You’ll also get mostly correct behaviour for c(). The exception is when you use c() with a base R class:

Unfortunately there’s no way to fix this problem with the current design of c().

Decimal class

Now that you’ve seen the basics with a very simple S3 class, we’ll gradually explore more complicated scenarios. This section creates a decimal class that prints with the specified number of decimal places. This is very similar to percent but now the class needs an attribute: the number of decimal places to display (an integer vector of length 1).

We start of as before, defining a low-level constructor, a user-friendly constructor, a format() method, and a vec_ptype_abbr(). Note that additional object attributes are simply passed along to new_vctr():

Note that I provide a little helper to extract the digits attribute. This makes the code a little easier to read, and should not be exported.

By default, vctrs assumes that attributes are independent of the data, and so are automatically preserved. You’ll see what to do if the attributes are data dependent in the next section.

For the sake of exposition, we’ll assume that digits is an important attribute of the class, and should be included in the full type:

Now consider vec_cast() and vec_type2(). I start with the standard recipes:

Casting and coercing from one decimal to another requires a little thought as the values of the digits attribute might be different, and we need some way to reconcile them. Here I’ve chosen to chose the maximum of the two; other reasonable options are to take the value from the left-hand side or throw an error.

Finally, I can implement coercion to and from other types, like doubles. When automatically coercing, I choose the richer type (i.e. the decimal).

If type x has greater resolution than y, there will be some inputs that lose precision. These should generate warnings using warn_lossy_cast(). You can see that in action when casting from doubles to integers; only some doubles can become integers without losing resolution.

Cached sum class

The next level up in complexity is an object that has data-dependent attributes. To explore this idea we’ll create a vector that caches the sum of its values. As usual, we start with low-level and user-friendly constructors:

For this class, we can use the default format() method, and instead, we’ll customise the obj_print_footer() method. This is a good place to display user facing attributes.

We’ll also override sum() and mean() to use the attribute. This is easiest to do with vec_math(), which you’ll learn about later.

As mentioned above, vctrs assumes that attributes are independent of the data. This means that when we take advantage of the default methods, they’ll work, but return the incorrect result:

To fix this, you need to provide a vec_restore() method. Note that this method dispatches on the to argument.

This works because most of the vctrs methods dispatch to the underlying base function, by first stripping off extra attributes with vec_data() and then reapplying them again with vec_restore(). The default vec_restore() method copies over all attributes, which is not appropriate when the attributes depend on the data.

Note that vec_restore.class is subtly different from vec_cast.class.class(). vec_restore() is used when restoring attributes that have been lost; vec_cast() is used for coercions. This is easier to understand with a concrete example. Imagine factors were implements with new_vectr(). vec_restore.factor() would restore attributes back to an integer vector, but you would not want to allow manually casting an integer to a factor with vec_cast(). ## Record-style objects

Record-style objects use a list of equal-length vectors to represent individual components of the object. The best example of this is POSIXlt, which underneath the hood is a list of 11 fields like year, month, and day. Record-style classes override length() and subsetting methods to conceal this implementation detail.

vctrs makes it easy to create new record-style classes using new_rcrd(), which has a wide selection of default methods.

Rational class

A fraction, or rational number can be represented by a pair of integer vectors representing the numerator (the number on top) and the denominator (the number on bottom), where the length of each vector must be the same. To represent such a data structure we turn to a new base data type: the record (or rcrd for short).

As usual we start with low-level and user-friendly constructors. The low-level constructor calls new_rcrd() which needs a named list of equal-length vectors.

Our user friendly constructor casts n and d to integers and recycles them to the same length.

Behind the scenes, x is a named list with two elements. But those details are hidden so that it behaves like a vector:

To access the underlying fields we need to use field() and fields():

This allows us to create a format method:

vctrs uses the format() method in str(), hiding the underlying implementation details from the user:

For rational, vec_type2() and vec_cast() follow the same pattern as percent(). I allow coercion from integer and to doubles.

Decimal2 class

The previous implementation of decimal was built on top of doubles. This is a bad idea because decimal vectors are typically used when you care about precise values (i.e. dollars and cents in a bank account), and double values suffer from floating point problems.

A better implementation of a decimal class would be to use pair of integers, one for the value to the left of the decimal point, and the other for the value to the right (divided by a scale). The code is a very quick sketch of how you might start creating such a class:

Equality and comparison

vctrs provides two “proxy” generics that lets you control how your class determines equality and ordering:

It’s a good idea to define methods for these generics because you get a lot of behaviour for relatively little work.

These proxy functions should always return a simple object (typically either a bare vector or a data frame), that possesses the same properties as your class. This permits efficient implementation of the vctrs internals because it allows dispatch to happen once in R, and then efficient computations can be written in C.

Rational class

Let’s explore these ideas by with the rational class we started on above. By default, vec_proxy_equal() converts a record to a data frame, and the default comparison works column by column:

This makes sense as a default, but isn’t correct here because rational(1, 1) represents the same number as rational(2, 2) so they should be equal. We can fix that by implementation vec_proxy_equal() method that by divides n and d by their greatest common divisor:

vec_proxy_equal() is also used by unique():

We need fix sort() similarly, since it currently sorts by n, then by d:

The easiest fix is to convert the fraction to a decimal and then sort that:

(We could have used the same approach in vec_proxy_equality(), but when working with floating point numbers it’s not necessarily true that x == y implies that d * x == d * y.)

Polynomial class

A related problem occurs if we build our vector on top of a list. The following code defines a polynomial class that represents polynomials (like 1 + 3x - 2x^2) using a list of integer vectors (like c(1, 3, -2)).

Equality works out of the box because we can tell if two integer vectors are equal:

But we can’t order them, because lists are not comparable:

So we need to define a vec_proxy_compare() method:

Arithmetic

vctrs also provides two mathematical generics that allow you to define a broad swath of mathematical behaviour at once:

Both generics define the behaviour for multiple functions because sum.vctrs_vctr(x) calls vec_math.vctrs_vctr("sum", x), and x + y calls vec_math.x_class.y_class("+", x, y). They’re accompanied by vec_math_base() and vec_arith_base() which make it easy to call the underlying base R functions.

vec_arith() uses double dispatch, and needs the following standard boilerplate:

vec_arith.MYCLASS <- function(op, x, y) {
  UseMethod("vec_arith.MYCLASS", y)
}
vec_arith.MYCLASS.default <- function(op, x, y) {
  stop_incompatible_op(op, x, y)
}

Cached sum class

I showed an example of vec_math() to define sum() and mean() methods cached_sum. Now lets talk about exactly how it works. Most vec_math() functions will have a similar form. You use a switch statement to handle the methods that you care about, and fall back to vec_math_base() for those that you don’t care about.

Meter class

To explore the infix arithmetic operators exposed by vec_arith() I’ll create a new class that represents a measurement in meters:

Because meter is built on top of a double vector, basic mathematic operations work:

But we can’t do arithmetic:

To allow these infix functions to work, we’ll need to provide vec_arith() generic. But before we do that, lets think about what combinations of inputs we should support:

vec_arith() is another function that uses double dispatch, so as usual we start with a template.

Then write the method for two meter objects. We use a switch statement to cover the cases we care about, and stop_incompatible_op() to throw an informative error message for everything else.

Next we write the pair of methods for arithmetic with a meter and a number. These are almost identical, but while meter(10) / 2 makes sense, 2 / meter(10) does not (as addition and subtraction).

For completeness, we also need vec_arith.vctrs_meter.MISSING for the unary + and - operators:

Appendix: NAMESPACE declarations

Defining S3 methods interactively is fine for iteration and exploration, but if your vector lives in a package, you also need to register the S3 methods by listing them in the NAMESPACE file. The namespace declarations are a little tricky because (e.g.) vec_cast.vctrs_percent() is both a generic function (which must be exported with export()) and an S3 method (which must be registered with S3method()).

This problem wasn’t considered in the design of roxygen2, so you have to be quite explicit:

#' @export
#' @method vec_cast vctrs_percent
#' @export vec_cast.vctrs_percent
vec_cast.vctrs_percent <- function(x, y) {
} 

You also need to register the individual double-dispatch methods. Again, this is harder than it should be because roxygen’s heuristics aren’t quite right. That means you need to describe the @method explicitly:

#' @method vec_cast.binned double
#' @export
vec_cast.binned.double <- function(x, y) {
}

Hopefully future versions of roxygen will make these exports less painful.