A Guide to Working with Quantities

Iñaki Ucar



This document intends to be a guide on how to work with quantities data (magnitudes with units and/or uncertainty) in two distinct workflows: R base and the so-called tidyverse. Units and errors (and, by extension, quantities) objects essentially are numeric vectors, arrays and matrices with associated metadata. This metadata is not always compatible with some functions, and thus we here explore the most common operations in data wrangling (subsetting, ordering, transformations, aggregations…) to identify potential issues and propose possible workarounds.

Let us consider the traditional iris data set for this exercise. According to its documentation,

iris is a data frame with 150 cases (rows) and 5 variables (columns) named Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, and Species.

And values are provided in centimeters. If we consider, for instance, a 5% of uncertainty, the first step is to define proper quantities. Then we will work on the resulting data frame for the rest of this article.

#> Loading required package: units
#> udunits system database from /usr/share/udunits
#> Loading required package: errors

iris.q <- iris
for (i in 1:4)
  quantities(iris.q[,i]) <- list("cm", iris.q[,i] * 0.05)
#>   Sepal.Length Sepal.Width Petal.Length  Petal.Width Species
#> 1  5.1(3) [cm] 3.5(2) [cm] 1.40(7) [cm] 0.20(1) [cm]  setosa
#> 2  4.9(2) [cm] 3.0(2) [cm] 1.40(7) [cm] 0.20(1) [cm]  setosa
#> 3  4.7(2) [cm] 3.2(2) [cm] 1.30(6) [cm] 0.20(1) [cm]  setosa
#> 4  4.6(2) [cm] 3.1(2) [cm] 1.50(8) [cm] 0.20(1) [cm]  setosa
#> 5  5.0(2) [cm] 3.6(2) [cm] 1.40(7) [cm] 0.20(1) [cm]  setosa
#> 6  5.4(3) [cm] 3.9(2) [cm] 1.70(8) [cm] 0.40(2) [cm]  setosa

Note that, throughout this document, and unless otherwise stated, we will talk about quantities objects as a shortcut for quantities, units and errors objects.

R Base

In this section, we consider all the methods and functions included in the default packages, i.e., those that are automatically installed along with any R distribution:

#>  [1] "base"      "compiler"  "datasets"  "graphics"  "grDevices"
#>  [6] "grid"      "methods"   "parallel"  "splines"   "stats"    
#> [11] "stats4"    "tcltk"     "tools"     "utils"

Row Subsetting

Quantities objects have all the subsetting methods defined ([, [[, [<-, [[<-). Therefore they can be used in the same way as with plain numeric vectors, and in conjunction with which and other functions to perform subsetting. The subset function is very handy too and achieves the same result:

Note that another quantities object is defined for the comparison. This is needed because different units are incomparable. Also note that the first line throws a warning telling us that the uncertainty was dropped for this operation. This kind of warning is thrown once, and this is why subset succeeds silently.

Row Ordering

The sort function, as its name suggests, sorts vectors, and it is compatible with quantities:

More generally, the order function can be used for data frame ordering:

Column Transformation

The transform function is able to modify variables in a data frame or to create new ones. The within function provides a similar but more flexible approach though. Both are fully compatible with quantities:

Row Aggregation

Row aggregation is the process of summarising data based on some grouping variable(s). There are several ways of working with data split by factors in R base, and, although they tend to preserve classes, they are generally not very kind to other metadata (i.e., attributes) by default.

In the following example, the average Sepal.Length is computed per Species, but the metadata gets dropped:

Many of these functions include a simplify parameter which, if set to FALSE, preserves quantities metadata:

The only drawback is that the result is a list, and such a list must be unlisted with care, otherwise, metadata gets dropped again:

The by function is an object-oriented wrapper for tapply applied to data frames which also provides a simplify parameter. A more convenient way of working with summary statistics is the aggregate generic, from the stats namespace. Although there is a aggregate.data.frame method, there is a more intuitive interface to it through the aggregate.formula method. Again, it is necessary to set simplify=FALSE to keep quantities:

Apparently, the output has no metadata associated, but what really happens is that the resulting columns are lists:

Therefore, as in the tapply/by case, they must be unlisted with care to still preserve the metadata:

And this method works for the tapply/by case too:

Column Joining

Joining data frames by common columns can done with the merge generic. Such operations are based on appending columns, which may be subset or replicated to fit the length of the merged observations. Therefore, quantities should be preserved in all cases. In the following example, we generate a data frame with the height per species and then merge it with the main data set:


The reshape function, from the stats namespace, provides an interface for both pivoting and unpivoting (i.e., tidyfying data). In the case of the iris data set, we would say that it is in the wide format, because each row has more than one observation.

This function has a quite peculiar nomenclature. First of all, the unpivoting operation is accessed by providing the argument direction="long". We need to define the varying columns (columns to unpivot), as character or indices, and they are unpivoted based on their names. By default, the separator sep="." is used, which means that Sepal.Width will be broken down into Sepal and Width, and the former will be unpivoted with the latter as grouping variable. We can specify the name of the grouping variable with the timevar argument.

Putting everything together, this is how to unpivot the data set by the dimension (which we will call it dim) of the petal/sepal:

It can be noted that the unpivoting also generates an index to indentify multiple records from the same group. We have changed the name of that identifier to dim.id (just id by default).

We can further unpivot sepal and petal as the part of the flower. First, we need to prepend a common identifier to columns 3 and 4, which are to be unpivoted:

And the final result has one tidy observation per row.

The pivoting operation can be accessed by providing the argument direction="wide". The process is almost symmetrical, but we need to specify v.names, as character, instead of varying columns. First, we can pivot by flower part:

Then, we remove "value." from the column names and pivot by dimension (note that indices are removed to match the initial data frame):

We have seen that quantities have been correctly preserved through the whole process. Finally, we can check whether both data frames are identical. Given that the order of columns have changed, we can simply check this column name by column name and then put everything together:


The core tidyverse includes the following packages: ggplot2, dplyr, tidyr, readr, purrr, tibble, stringr and forcats. This section covers use cases for dplyr (everything except for pivoting and unpivoting) and tidyr (for pivoting and unpivoting).

library(dplyr); packageVersion("dplyr")
#> [1] '0.7.6'
library(tidyr); packageVersion("tidyr")
#> [1] '0.8.1'

Row Subsetting

The filter generic finds observations where conditions hold. The main difference with base subsetting is that, if a condition evaluates to NA for a certain row, it is dropped. As in the base case, another quantities object must be defined for the comparison:

There are also three scoped variants available (filter_all, filter_if, filter_at) and a subsetting function by row number called slice. All of them preserve quantities.

Row Ordering

The arrange generic sorts variables in a straightforward way, and it is compatible with quantities:

The desc function can be applied to individual variables to arrange in descending order.

Column Transformation

There are two generics for column transformations: mutate modifies or adds new variables preserving the existing ones, while transmute drops the existing variables. The syntax is very similar to base functions transform and within, and equally compatible with quantities:

Row Aggregation

dplyr breaks down aggregation operations in two distinct parts: grouping (with group_by) and summarising (using summarise and others). The shortcoming of this approach is that it is possible to apply other operations (such as subsetting) to grouped data, which may lead to performance degradation.

Another shortcoming is that dplyr’s grouped operations are not yet fully compatible with quantities (see tidyverse/dplyr#2773):

As we can see above, although units are correctly preserved, uncertainty is not correctly handled.

Units alone work without issue, but errors or full-featured quantities are not compatible with dplyr’s grouped operations.

Column Joining

Several verbs are provided for different types of joins, such as inner_join, left_join, right_join or full_join. It seems that, internally, they use the same grouping mechanism than summaries, and therefore they will generally fail for errors and full-featured quantities (note the missing uncertainty, as in the previous case):


Finally, pivoting and unpivoting is handled by a separate package, tidyr, using the verbs spread (pivot) and gather (unpivot).

The unpivoting operation is substantially more straightforward. In the next example, we directly merge the four columns of interest into the value column, and the correspoding column names are gathered into the key column. Such a column is then separated into flower part (sepal, petal) and dim (length, height):

Unfortunately, it is evident that the operation completely drops all classes and attributes, and then quantities are not preserved.

The pivoting operation does preserve classes and attributes, but the latter ones are not correctly handled. In the following example, we first gather the original data set, then we assign quantities and try to spread it to obtain iris.q:

Apparently, everything worked, but in fact it didn’t:

As shown above, the uncertainty was not properly subset and pivoted.


R base works smoothly with quantities in most cases. The only shortcoming is that some care must be applied to aggregations. In particular, simplification must be explicitly disabled (simplify=FALSE), and such a simplification (i.e., converting lists to vectors of quantities) must be applied manually while avoiding unlist.

The tidyverse handles quantities correctly for subsetting, ordering and transformations. It fails to do so for aggregations (grouped operations in general), column joining and (un)pivoting. Most of these incompatibilities are due to the same internal grouping mechanism, which is in C and prevents the R subsetting operator from being called (which in turn calls the subsetting operator on the errors attribute). Interestingly, those operations still work for units alone, except for column gathering, which drops all classes and attributes.

A Note on data.table

The data.table package is another popular data tools, which provides a high-performance version of base R’s data.frame with syntax and feature enhancements for ease of use, convenience and programming speed.

Long story short, we have not included a section on data.table because currently (v1.11.4) it does not work well with vectorised attributes. The underlying problem is similar to dplyr’s issue, but unfortunately it affects more operations, including row subsetting and ordering. Only column transformation seems to work, and other operations generate corrupted objects.

We have found that defining quantities columns as lists (where each element consists of a single value, with unit and uncertainty) may be a workaround, but this probably would be a serious performance penalty for a package that is typically chosen for speed reasons.