Debian Codegraph @

inst/doc/measurement_units_in_R.Rmd

raw
1 ---
2 title: "Measurement units in R"
3 author: "Edzer Pebesma, Thomas Mailund, and James Hiebert"
4 output:
5 rmarkdown::html_vignette:
6 toc: yes
7 bibliography: measurement_units_in_R.bib
8 link-citations: yes
9 vignette: >
10 %\VignetteIndexEntry{Measurement units in R}
11 %\VignetteEngine{knitr::rmarkdown}
12 %\VignetteEncoding{UTF-8}
13 ---
14
15 ```{r echo=FALSE}
16 knitr::opts_chunk$set(collapse = TRUE, fig.asp = 0.7, fig.width = 7)
17 ```
18
19 This vignette is identical to @rj, except for two changes:
20
21 * it has been synchronized with updates to the [units](https://cran.r-project.org/package=units) package
22 * it has been converted to R-markdown
23
24 ## Abstract
25 We briefly review SI units, and discuss R packages that deal
26 with measurement units, their compatibility and conversion.
27 Built upon the UNIDATA udunits library, we introduce the package
28 [units](https://cran.r-project.org/package=units) that provides a
29 class for maintaining unit metadata. When used in expression, it
30 automatically converts units, and simplifies units of results when
31 possible; in case of incompatible units, errors are raised. The
32 class flexibly allows expansion beyond predefined units. Using
33 [units](https://cran.r-project.org/package=units) may eliminate a
34 whole class of potential scientific programming mistakes. We discuss
35 the potential and limitations of computing with explicit units.
36
37
38 ## Introduction
39
40 Two quotes from @cobb -- _Data are not just numbers,
41 they are numbers with a context_ and _in data analysis,
42 context provides meaning_ -- illustrate that for a data analysis
43 to be meaningful, knowledge of the data's context is needed.
44 Pragmatic aspects of this context include who collected or generated
45 the data, how this was done, and for which purpose [@scheider];
46 semantic aspects concern what the data represents: which aspect
47 of the world do the data refer to, when and where were they measured,
48 and what a value of `1` means.
49
50 R does allow for keeping some context with data, for instance
51
52 * `data.frame` columns must have and `list` elements may have names that can be used to describe context, using freetext
53 * `matrix` or `array` objects may have `dimnames`
54 * for variables of class `factor` or `ordered`, `levels` may indicate, using freetext, the categories of nominal or ordinal variables
55 * `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)
56 * `difftime` objects specify how time duration can be represented by numbers, with flexible units (secs, mins, hours, days, weeks); [lubridate](https://cran.r-project.org/package=lubridate) [@lubridate] extends some of this functionality.
57
58 Furthermore, if spatial objects as defined in package
59 [sp](https://cran.r-project.org/package=sp) [@sp] have a proper
60 coordinate reference system set, they can be transformed to other
61 datums, or converted to various flat (projected) representations
62 of the Earth [@iliffe].
63
64 In many cases however, R drops contextual information. As an example, we
65 look at annual global land-ocean temperature index (from
66 `http://climate.nasa.gov/vital-signs/global-temperature/`) since 1960:
67 ```{r}
68 temp_data = subset(read.table("647_Global_Temperature_Data_File.txt",
69 header=TRUE)[1:2], Year >= 1960)
70 temp_data$date = as.Date(paste0(temp_data$Year, "-01-01"))
71 temp_data$time = as.POSIXct(temp_data$date)
72 Sys.setenv(TZ="UTC")
73 head(temp_data, 3)
74 year_duration = diff(temp_data$date)
75 mean(year_duration)
76 ```
77
78 Here, the time difference units are reported for the `difftime`
79 object `year_duration`, but if we would use it in a linear algebra operation
80 ```{r}
81 year_duration %*% rep(1, length(year_duration)) / length(year_duration)
82 ```
83 the unit is dropped. Similarly, for linear regression coefficients we see
84 ```{r}
85 coef(lm(Annual_Mean ~ date, temp_data))
86 coef(lm(Annual_Mean ~ time, temp_data))
87 ```
88 where the unit of change is in degrees Celsius but either _per
89 day_ (`date`) or _per second_ (`time`). For purely mathematical
90 manipulations, R often strips context from numbers when it is carried
91 in attributes, the linear algebra routines being a prime example.
92
93 Most variables are somehow attributed with information about
94 their _units_, which specify what the value `1` of this variable
95 represents. This may be counts of something, e.g. `1 apple`,
96 but it may also refer to some _physical unit_, such as distance
97 in meter. This article discusses how strong unit support can be
98 introduced in R.
99
100 ## SI
101
102 The [BIPM](https://www.bipm.org/) (Bureau International des Poids et
103 Mesures) is "_the intergovernmental organization through which
104 Member States act together on matters related to measurement science
105 and measurement standards. Its recommended practical system of units
106 of measurement is the International System of Units (Système International
107 d'Unités, with the international abbreviation SI)_
108 (https://www.bipm.org/en/measurement-units/)".
109
110 @si describe the SI units, where, briefly, _SI units_
111
112 * 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 (see table below)
113 * 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}$)
114 * consist of _coherent derived units_ when derived units include no numerical factors other than one (with the exception of `kg`; as a base unit, kg can be part of coherent derived units); an example of a coherent derived unit is 1 watt = 1 joule per 1 second,
115 * may contain SI prefixes (k = kilo for $10^3$, m = milli for $10^{-3}$, etc.)
116 * contain special quantities where units disappear (e.g., m/m) or have the nature of a count, in which cases the unit is 1.
117
118 base quantities, SI units and their symbols (from @si, p. 23):
119
120 | Base quantity | | SI base unit | |
121 | -----------|--------|----------|------|
122 | Name |Symbol|Name | Symbol
123 | length | $l,x,r,$ etc.| meter | m |
124 | mass | $m$ | kilogram | kg |
125 | time, duration | $t$ | second | s |
126 | electric current| $I, i$ | ampere | A |
127 | thermodynamic temperature | $T$ | kelvin | K |
128 | amount of substance | $n$ | mole | mol |
129 | luminous intensity | $I_v$ | candela | cd |
130
131 ## Related work in R
132
133 Several R packages provide unit conversions.
134 For instance, [measurements](https://cran.r-project.org/package=measurements) [@measurements] provides
135 a collection of tools to make working with physical measurements
136 easier. It converts between metric and imperial units, or calculates
137 a dimension's unknown value from other dimensions' measurements. It
138 does this by the `conv_unit` function:
139 ```{r, eval=requireNamespace("measurements", quietly=TRUE)}
140 library(measurements)
141 conv_unit(2.54, "cm", "inch")
142 conv_unit(c("101 44.32","3 19.453"), "deg_dec_min", "deg_min_sec")
143 conv_unit(10, "cm_per_sec", "km_per_day")
144 ```
145 but uses for instance `kph` instead of `km_per_hour`, and then
146 `m3_per_hr` for flow -- unit names seem to come from convention rather
147 than systematic composition. Object
148 `conv_unit_options` contains all 173 supported units, categorized by
149 the physical dimension they describe:
150 ```{r, eval=requireNamespace("measurements", quietly=TRUE)}
151 names(conv_unit_options)
152 conv_unit_options$volume
153 ```
154 Function `conv_dim` allows for the conversion of units in products or ratios,
155 e.g.
156 ```{r, eval=requireNamespace("measurements", quietly=TRUE)}
157 conv_dim(x = 100, x_unit = "m", trans = 3, trans_unit = "ft_per_sec", y_unit = "min")
158 ```
159 computes how many minutes it takes to travel 100 meters at 3 feet per second.
160
161 Package [NISTunits](https://cran.r-project.org/package=NISTunits) [@NISTunits] provides fundamental
162 physical constants (Quantity, Value, Uncertainty, Unit) for SI and
163 non-SI units, plus unit conversions, based on the data from NIST
164 (National Institute of Standards and Technology). The package
165 provides a single function for every
166 unit conversion; all but 5 from its 896 functions are of the form
167 `NISTxxxTOyyy` where `xxx` and `yyy` refer to two
168 different units. For instance, converting from W m$^{-2}$ to W inch$^{-2}$
169 is done by
170 ```{r, eval=requireNamespace("NISTunits", quietly=TRUE)}
171 library(NISTunits)
172 NISTwattPerSqrMeterTOwattPerSqrInch(1:5)
173 ```
174 Both [measurements](https://cran.r-project.org/package=measurements) and [NISTunits](https://cran.r-project.org/package=NISTunits) are written entirely
175 in R.
176
177 ## UNIDATA's udunits library
178
179 Udunits, developed by UCAR/UNIDATA, advertises itself on [its web
180 page](https://www.unidata.ucar.edu/software/udunits)
181 as: "_The udunits package supports units of physical
182 quantities. Its C library provides for arithmetic manipulation
183 of units and for conversion of numeric values between compatible
184 units. The package contains an extensive unit database, which is
185 in XML format and user-extendable._"
186
187 Unlike the
188 [measurements](https://cran.r-project.org/package=measurements)
189 and [NISTunits](https://cran.r-project.org/package=NISTunits),
190 the underlying udunits2 C library parses
191 units as expressions, and bases its logic upon the convertibility
192 of expressions, rather than the comparison of fixed strings:
193 ```{r}
194 m100_a = paste(rep("m", 100), collapse = "*")
195 dm100_b = "dm^100"
196 units::ud_are_convertible(m100_a, dm100_b)
197 ```
198 This has the advantage that through complex computations,
199 intermediate objects can have units that are arbitrarily complex,
200 and that can potentially be simplified later on. It also means that
201 the package practically supports an unlimited amount of derived units.
202
203 ## Udunits versus the Unified Code for Units of Measure (UCUM)
204
205 Another set of encodings for measurement units is the Unified Code for
206 Units of Measure (UCUM, @ucum). A dedicated web
207 site\footnote{\url{http://coastwatch.pfeg.noaa.gov/erddap/convert/units.html}}
208 describes the details of the differences between udunits and UCUM,
209 and provides a conversion service between the two encoding sets.
210
211 The UCUM website refers to some Java implementations, but some of the
212 links seem to be dead. UCUM is the preferred encoding for standards
213 from the Open Geospatial Consortium. udunits on the other hand
214 is the units standard of choice by the climate science community,
215 and is adopted by the CF (Climate and Forecast) conventions, which
216 mostly uses NetCDF. NetCDF [@netcdf] is a binary data format
217 that is widely used for atmospheric and climate model predictions.
218
219 The udunits library is a C library that has strong support from
220 UNIDATA, and we decided to build our developments on this, rather
221 than on Java implementations of UCUM with a less clear provenance.
222
223 ## Handling data with units in R: the units package
224
225 The [units](https://cran.r-project.org/package=units) package builds `units` objects from scratch,
226 e.g. where
227 ```{r}
228 library(units)
229 x = set_units(1:5, m/s)
230 str(x)
231 ```
232 represents speed values in `m/s`. The units `m` and `s` are resolved
233 from the udunits2 C library (but could be user-defined units).
234
235 Units can be used in arbitrary R expressions like
236 ```{r}
237 set_units(1:3, m/s^2)
238 ```
239
240 Several manipulations with `units` objects will now be illustrated.
241 Manipulations that do not involve unit conversion are for instance addition:
242 ```{r}
243 x = set_units(1:3, m/s)
244 x + 2 * x
245 ```
246 Explicit unit conversion is done by assigning new units:
247 ```{r}
248 (x = set_units(x, cm/s))
249 as.numeric(x)
250 ```
251 similar to the behaviour of `difftime` objects, this modifies
252 the numeric values without modifying their meaning (what the numbers
253 refer to).
254
255 When mixing units in sums, comparisons or concatenation, units are
256 automatically converted to those of the first argument:
257 ```{r}
258 y = set_units(1:3, km/h)
259 x + y
260 y + x
261 x == y
262 c(y, x)
263 ```
264 where `c(y, x)` concatenates `y` and `x` after converting `x` to the
265 units of `y`. Derived units are created where appropriate:
266 ```{r}
267 x * y
268 x^3
269 ```
270 and meaningful error messages appear when units are not compatible:
271 ```{r}
272 e = try(z <- x + x * y)
273 attr(e, "condition")[[1]]
274 ```
275 The full set of methods and method groups for `units` objects is shown by
276 ```{r}
277 methods(class = "units")
278 ```
279 where the method groups
280
281 * `Ops` include operations that require compatible units, converting when necessary (`+`, `-`, `==`, `!=`, `<`, `>`, `<=`, `>=`), and operations that create new units (`*`, `/`, `^` and `**`),
282 * `Math` include `abs`, `sign`, `floor`, `ceiling`, `trunc`, `round`, `signif`, `log`, `cumsum`, `cummax`, `cummin`, and
283 * `Summary` include `sum`, `min`, `max` and `range`, and all convert to the unit of the first argument.
284
285 When possible, new units are simplified:
286 ```{r}
287 a = set_units(1:10, m/s)
288 b = set_units(1:10, h)
289 a * b
290 ustr1 = paste(rep("m", 101), collapse = "*")
291 ustr2 = "dm^100"
292 as_units(ustr1) / as_units(ustr2)
293 ```
294
295 Units are printed as simple R expressions, e.g.
296 ```{r}
297 set_units(1, m^5/s^4)
298 ```
299 Another way to print units commonly seen in Climate and Forecast Conventions\footnote{CF, \url{http://cfconventions.org/Data/cf-standard-names/34/build/cf-standard-name-table.html}} is `m2 s-1` for m$^2$/s. These are not R expressions, but they can be parsed by `as_units`, and created by `deparse_unit`:
300 ```{r}
301 as_units("m2 s-1")
302 deparse_unit(set_units(1, m^2*s^-1))
303 ```
304 The `plot` and `hist` methods add units to default axis labels, an
305 example is shown in the following figures. For [ggplot2](https://cran.r-project.org/package=ggplot2) plots
306 [@ggplot2], automatic unit placement in default axis label is also provided; `demo(ggplot2)` gives an example.
307
308 ```{r}
309 library(units)
310 units_options(negative_power = TRUE)
311 # initialize variables with units:
312 mtcars$consumption = set_units(mtcars$mpg, mi/gallon)
313 # "in" is also a reserved R keyword, and so needs back-quotes:
314 mtcars$displacement = set_units(mtcars$disp, `in`^3)
315 # convert to SI:
316 mtcars$consumption = set_units(mtcars$consumption, km/l)
317 mtcars$displacement = set_units(mtcars$displacement, cm^3)
318 par(mar = par("mar") + c(0, .3, 0, 0))
319 with(mtcars, plot(1/displacement, 1/consumption))
320 ```
321
322 ```{r, eval=requireNamespace("ggplot2", quietly=TRUE)}
323 library(ggplot2)
324 ggplot(mtcars) + geom_point(aes(x = 1/displacement, y = 1/consumption))
325 ```
326
327 Automatic conversion between `units` and `difftime` is provided:
328 ```{r}
329 (dt = diff(Sys.time() + c(0, 1, 1+60, 1+60+3600))) # class difftime
330 (dt.u = as_units(dt))
331 identical(as_difftime(dt.u), dt)
332 ```
333 as well as to and from `POSIXct` or `Date`:
334 ```{r}
335 (t1 <- as_units(as.POSIXct("2017-08-20 17:03:00")))
336 (t2 <- as_units(as.POSIXct("2017-08-20 17:03:00"), "hours since 2017-08-20"))
337 (d1 <- as_units(as.Date("2017-08-20")))
338 as.POSIXct(t1)
339 as.Date(d1)
340 ```
341 Objects of class `units` can be used as columns in `data.frame`
342 objects, as well as in `tbl_df` [@tibble]. They can also be `matrix`
343 or `array`, with the constraint that a single unit holds for all
344 elements.
345
346 ## Discussion and conclusions
347
348 The [units](https://cran.r-project.org/package=units) R package provides a new class, `units`,
349 for numeric data with associated measurement units. Operations
350 on objects of this class retain the unit metadata and provide
351 automated dimensional analysis: dimensions are taken into consideration
352 in computations and comparisons. Combining different units that are
353 compatible triggers automatic unit conversion, derived units
354 are automatically generated and simplified where possible, and
355 meaningful error messages are given when a user tries to add objects
356 with incompatible units. This verifies that computations are not
357 only syntactically and numerically allowed, but also semantically,
358 and in the case of physical units, physically allowed, which may
359 support code verification and provenance tracking. Using this
360 package may eliminate a whole class of potential scientific
361 programming mistakes.
362
363 Where the R packages
364 [measurements](https://cran.r-project.org/package=measurements)
365 and [NISTunits](https://cran.r-project.org/package=NISTunits)
366 provide conversion between a fixed number of units, with
367 the help of the udunits2 C library and unit database, R package
368 [units](https://cran.r-project.org/package=units) handles
369 arbitrarily complex derived units. By treating units as expressions
370 it can derive, convert and simplify units. In addition, beyond the
371 SI units packaged, [units](https://cran.r-project.org/package=units)
372 handles user-defined units.
373
374 Data in `units` vectors can be stored as columns in
375 `data.frame` or `tbl_df` objects, and can be
376 converted to and from `difftime`. When `units`
377 objects have associated time and location information,
378 they could be stored in spatial or spatio-temporal objects
379 provided by [sp](https://cran.r-project.org/package=sp) or
380 [spacetime](https://cran.r-project.org/package=spacetime)
381 [@spacetime] as these store attribute data in
382 `data.frame` slots, but for instance not in `zoo`
383 [@zoo] or `xts` [@xts] objects, as these latter
384 two set the class attribute of a vector or matrix.
385
386 Despite all standardization efforts, units may still be ambiguous,
387 or subject to interpretation. For instance for the duration of one
388 year [NISTunits](https://cran.r-project.org/package=NISTunits) gives
389 us an answer that depends on whether we want a common, leap,
390 Gregorian, Julian, tropical or siderial year (@lang, see
391 also `demo(year)`). This illustrates that those who apply
392 unit conversion should be aware of possible pitfalls. Support for
393 calendars in udunits seems not as well developed as in R.
394
395 Future work includes extending packages that read external
396 data from formats, databases or interfaces with support for
397 measurement unit information into R, preserving the measurement
398 unit information. Examples would be interfaces to HDF5 (e.g.,
399 [h5](https://cran.r-project.org/package=h5), @h5),
400 [RNetCDF](https://cran.r-project.org/package=RNetCDF) [@RNetCDF]
401 or [sos4R](https://cran.r-project.org/package=sos4R) [@sos4R].
402 It would be nice to see units of measurements propagate into units
403 of regression coefficient estimates.
404
405 ## Acknowledgements
406
407 We acknowledge three anonymous reviewers and the handling editor for
408 their constructive comments, and Thomas Lin Pedersen for implementing
409 the ggplot extensions in package `ggforce` (ported to the `units` package
410 since v0.8-0) that automatically add units to default ggplot axis labels.
411
412 ## References