Measurement Units in R by

We briefly review SI units, and discuss R packages that deal with measurement units, their compatibility and conversion. Built upon udunits2 and the UNIDATA udunits library, we introduce the package units that provides a class for maintaining unit metadata. When used in expression, it automatically converts units, and simplifies units of results when possible; in case of incompatible units, errors are raised. The class flexibly allows expansion beyond predefined units. Using units may eliminate a whole class of potential scientific programming mistakes. We discuss the potential and limitations of computing with explicit units.


Introduction
Two quotes from Cobb and Moore (1997) -"Data are not just numbers, they are numbers with a context" and "in data analysis, context provides meaning" -illustrate that for a data analysis to be meaningful, knowledge of the data's context is needed.Pragmatic aspects of this context include who collected or generated the data, how this was done, and for which purpose (Scheider et al., 2016); semantic aspects concern what the data represents: which aspect of the world do the data refer to, when and where were they measured, and what a value of '1' means.
R does allow for keeping some context with data, for instance • "data.frame"columns must have and "list" elements may have names that can be used to describe context, using freetext • "matrix" or "array" objects may have dimnames • for variables of class "factor" or "ordered", levels may indicate, using freetext, the categories of nominal or ordinal variables • "POSIXt" and "Date" objects specify how numbers should be interpreted as time or date, with fixed units (second and day, respectively) and origin (Jan 1, 1970, 00:00 UTC) • "difftime" objects specify how time duration can be represented by numbers, with flexible units (secs, mins, hours, days, weeks); lubridate (Grolemund and Wickham, 2011) extends some of this functionality.
Furthermore, if spatial objects as defined in package sp (Pebesma and Bivand, 2005) have a proper coordinate reference system set, they can be transformed to other datums, or converted to various flat (projected) representations of the Earth (Iliffe and Lott, 2008).
In many cases however, R drops contextual information.As an example, we look at annual global land-ocean temperature index1 since 1960: > temp_data = subset(read.where the unit of change is in degrees Celsius but either per day (date) or per second (time).For purely mathematical manipulations, R often strips context from numbers when it is carried in attributes, the linear algebra routines being a prime example.
Most variables are somehow attributed with information about their units, which specify what the value 1 of this variable represents.This may be counts of something, e.g.'1 apple', but it may also refer to some physical unit, such as distance in meter.This article discusses how strong unit support can be introduced in R.

SI
The BIPM (Bureau International des Poids et Mesures) is the "the intergovernmental organization through which Member States act together on matters related to measurement science and measurement standards.Its recommended practical system of units of measurement is the International System of Units (Système International d'Unités, with the international abbreviation SI)2 ".International Bureau of Weights and Measures et al. (2001) describe the SI units, where, briefly, SI units • consist of seven base units (length, mass, time & duration, electric current, thermodynamic temperature, amount of substance, and luminous intensity), each with a name and abbreviation (Table 1) • consist of derived units that are formed by products of powers of base units, such as 'm/s 2 ', many of which have special names and symbols (e.g.angle: 1 rad = 1 m/m; force: 1 N = 1 m kg s −2 ) • consist of coherent derived units when derived units include no numerical factors other than one (with the exception of 'kg'3 ); an example of a coherent derived unit is 1 watt = 1 joule per 1 second, • may contain SI prefixes (k = kilo for 10 3 , m = milli for 10 −3 , etc.) • contain special quantities where units disappear (e.g., m/m) or have the nature of a count, in which cases the unit is '1'.

Related work in R
Several R packages provide unit conversions.For instance, measurements (Birk, 2016) provides a collection of tools to make working with physical measurements easier.It converts between metric and imperial units, or calculates a dimension's unknown value from other dimensions' measurements.
Package NISTunits (Gama, 2014) provides fundamental physical constants (Quantity, Value, Uncertainty, Unit) for SI and non-SI units, plus unit conversions, based on the data from NIST (National Institute of Standards and Technology).The package provides a single function for every unit conversion; all but 5 from its 896 functions are of the form 'NISTxxxTOyyy' where 'xxx' and 'yyy' refer to two different units.For instance, converting from W m −2 to W inch −2 is done by > library(NISTunits) > NISTwattPerSqrMeterTOwattPerSqrInch(1:5) [1] 0.00064516 0.00129032 0.00193548 0.00258064 0.00322580 Both measurements and NISTunits are written entirely in R.

UNIDATA's udunits library and the udunits2 R package
Udunits, developed by UCAR/UNIDATA, advertises itself on its web page4 as: "The udunits package supports units of physical quantities.Its C library provides for arithmetic manipulation of units and for conversion of numeric values between compatible units.The package contains an extensive unit database, which is in XML format and user-extendable.The R package udunits2 (Hiebert, 2015) provides an R level interface to the most important functions in the C library.
> ud.get.name("kg")[1] "kilogram" > ud.get.symbol("kilogram")[1] "kg" > ud.set.encoding("utf8")NULL Unlike the measurements and NISTunits, udunits2 parses units as expressions, and bases its logic upon the convertibility of expressions, rather than the comparison of fixed strings: This has the advantage that through complex computations, intermediate objects can have units that are arbitrarily complex, and that can potentially be simplified later on.It also means that the package practically supports an unlimited amount of derived units.

Udunits versus the Unified Code for Units of Measure (UCUM)
Another set of encodings for measurement units is the Unified Code for Units of Measure (UCUM, Schadow and McDonald (2009)).A dedicated web site5 describes the details of the differences between udunits and UCUM, and provides a conversion service between the two encoding sets.
The UCUM website refers to some Java implementations, but some of the links seem to be dead.UCUM is the preferred encoding for standards from the Open Geospatial Consortium.udunits on the other hand is the units standard of choice by the climate science community, and is adopted by the CF (Climate and Forecast) conventions, which mostly uses NetCDF.NetCDF (Rew and Davis, 1990) is a binary data format that is widely used for atmospheric and climate model predictions.
The udunits library is a C library that has strong support from UNIDATA, and we decided to build our developments on this, rather than on Java implementations of UCUM with a less clear provenance.

Handling data with units in R: the units package
The units package builds "units" objects from scratch, where m, created by > library(units) > m = make_unit("m") > str(m) Class units atomic [1:1] 1 ..-attr(*, "units")=List of 2 .. ..$ numerator : chr "m" .. ..$ denominator: chr(0) .. ..-attr(*, "class")= chr "symbolic_units" represents '1 m', one meter.Other length values are obtained by using this unit in an expression: As an alternative to using make_unit, we can retrieve units directly from the ud_units database, which is part of units, and was derived from the xml units database that is part of udunits.Two ways of doing this are Although one could attach ud_units to use the units directly, there are over 3000 and this would not only clobber the namespace but also lead to conflicts, e.g. for T (Tesla, TRUE) or in (inch, reserved R language element).The last form using with has the advantage that it can take direct expressions: > with(ud_units, m/s^2) 1 m/s^2 Several manipulations with "units" objects will now be illustrated.

Discussion and conclusions
The units R package provides a new class, "units", for numeric data with associated measurement units.Operations on objects of this class retain the unit metadata and provide automated dimensional analysis: dimensions are taken into consideration in computations and comparisons.Combining different units that are compatible triggers automatic unit conversion, derived units are automatically generated and simplified where possible, and meaningful error messages are given when a user tries to add objects with incompatible units.This verifies that computations are not only syntactically and numerically allowed, but also semantically, and in the case of physical units, physically allowed, which may support code verification and provenance tracking.Using this package may eliminate a whole class of potential scientific programming mistakes.
Where the R packages measurements and NISTunits provide conversion between a fixed number of units, with the help of the udunits library and unit database R package units allows for arbitrarily complex derived units.By treating units as expressions it can derive, convert and simplify units.In addition, beyond the SI units packaged, units handles user-defined units not supported by udunits.
Data in "units" vectors can be stored as columns in "data.frame"or "tbl_df" objects, and can be converted to and from "difftime".When "units" objects have associated time and location information, they could be stored in spatial or spatio-temporal objects provided by sp or spacetime (Pebesma, 2012) as these store attribute data in "data.frame"slots, but for instance not in "zoo" (Zeileis and Grothendieck, 2005) or "xts" (Ryan and Ulrich, 2014) objects, as these latter two set the class attribute of a vector or matrix.Despite all standardization efforts, units may still be ambiguous, or subject to interpretation.For instance for the duration of one year NISTunits or udunits2 give us an answer that depends on whether we want a common, leap, Gregorian, Julian, tropical or siderial year (Lang (2006), see also demo(year)).This illustrates that those who apply unit conversion should be aware of possible pitfalls.Support for calendars in udunits seems not as well developed as in R.
Future work includes extending packages that read external data from formats, databases or interfaces with support for measurement unit information into R, preserving the measurement unit information.Examples would be interfaces to HDF5 (e.g., h5, Annau (2016)), RNetCDF (Michna and Woods, 2016) or sos4R (Nüst et al., 2011).It would be nice to see units of measurements propagate into units of regression coefficient estimates.

Figure 1 :
Figure1: Plot of 1/consumption against 1/displacement of dataset mtcars, illustrating automatic units in default axis labels (after conversion to SI) for base plot (left) and ggplot (right); demo(ggforce) illustrates how these plots are generated.

table (
Here, the time difference units are reported for the difftime object year_duration, but if we would use it in a linear algebra operation

Table 1 :
base quantities, SI units and their symbols (from International Bureau of Weights andMeasures et al. (2001), p. 23) c(y,x) concatenates y and x after converting x to the units of y.Derived units are created where appropriate:The full set of methods and method groups for units objects is shown by where