| 1 |
--- |
| 2 |
title: "Units of Measurement for R Vectors: an Introduction" |
| 3 |
output: |
| 4 |
rmarkdown::html_vignette: |
| 5 |
toc: yes |
| 6 |
vignette: > |
| 7 |
%\VignetteIndexEntry{Units of Measurement for R Vectors: an Introduction} |
| 8 |
%\VignetteEngine{knitr::rmarkdown} |
| 9 |
%\VignetteEncoding{UTF-8} |
| 10 |
--- |
| 11 |
|
| 12 |
```{r echo=FALSE} |
| 13 |
knitr::opts_chunk$set(collapse = TRUE, fig.asp = 0.7, fig.width = 7) |
| 14 |
``` |
| 15 |
|
| 16 |
```{r echo=FALSE} |
| 17 |
units:::units_options(negative_power = FALSE) |
| 18 |
``` |
| 19 |
|
| 20 |
R has little support for physical measurement units. The exception |
| 21 |
is formed by time differences: time differences objects of class |
| 22 |
`difftime` have a `units` attribute that can be modified: |
| 23 |
|
| 24 |
```{r} |
| 25 |
t1 = Sys.time() |
| 26 |
t2 = t1 + 3600 |
| 27 |
d = t2 - t1 |
| 28 |
class(d) |
| 29 |
units(d) |
| 30 |
d |
| 31 |
units(d) = "secs" |
| 32 |
d |
| 33 |
``` |
| 34 |
We see here that the `units` method is used to retrieve and modify the |
| 35 |
unit of time differences. |
| 36 |
|
| 37 |
The `units` package generalizes this idea to other physical units, building upon the |
| 38 |
[udunits2](https://www.unidata.ucar.edu/software/udunits) C library. |
| 39 |
The `udunits2` library provides the following operations: |
| 40 |
|
| 41 |
* validating whether an expression, such as `m/s` is a valid physical unit |
| 42 |
* verifying whether two units such as `m/s` and `km/h` are convertible |
| 43 |
* converting values between two convertible units |
| 44 |
* providing names and symbols for specific units |
| 45 |
* handle different character encodings (utf8, ascii, iso-8859-1 and latin1) |
| 46 |
|
| 47 |
The `units` R package uses the |
| 48 |
[udunits2](https://www.unidata.ucar.edu/software/udunits) C library to extend |
| 49 |
R with functionality for manipulating numeric vectors that have |
| 50 |
physical measurement units associated with them, in a similar way as |
| 51 |
`difftime` objects behave. |
| 52 |
|
| 53 |
## Setting units, unit conversion |
| 54 |
|
| 55 |
We can set units to numerical values by `set_units`: |
| 56 |
```{r} |
| 57 |
library(units) |
| 58 |
(a <- set_units(runif(10), m/s)) |
| 59 |
``` |
| 60 |
the result, e.g. |
| 61 |
```{r} |
| 62 |
set_units(10, m/s) |
| 63 |
``` |
| 64 |
literally means "10 times 1 m divided by 1 s". In writing, the "1" |
| 65 |
values are omitted, and the multiplication is implicit. |
| 66 |
|
| 67 |
### Unit conversion |
| 68 |
|
| 69 |
When conversion is meaningful, such as hours to seconds or meters to kilometers, conversion can be done explicitly by setting the units of a vector |
| 70 |
```{r} |
| 71 |
b = a |
| 72 |
units(b) <- make_units(km/h) |
| 73 |
b |
| 74 |
``` |
| 75 |
|
| 76 |
## Basic manipulations |
| 77 |
|
| 78 |
### Arithmetic operations |
| 79 |
|
| 80 |
Arithmetic operations verify units, and create new ones |
| 81 |
```{r} |
| 82 |
a + a |
| 83 |
a * a |
| 84 |
a ^ 2 |
| 85 |
a ** -2 |
| 86 |
``` |
| 87 |
and convert to the units of the first argument if necessary: |
| 88 |
```{r} |
| 89 |
a + b # m/s + km/h -> m/s |
| 90 |
``` |
| 91 |
|
| 92 |
Currently, powers are only supported for integer powers, so using `a ** 2.5` would result in an error. |
| 93 |
|
| 94 |
|
| 95 |
### Unit simplification |
| 96 |
There are some basic simplification of units: |
| 97 |
```{r} |
| 98 |
t <- make_units(s) |
| 99 |
a * t |
| 100 |
``` |
| 101 |
which also work when units need to be converted before they can be simplified: |
| 102 |
```{r} |
| 103 |
t <- make_units(min) |
| 104 |
a * t |
| 105 |
``` |
| 106 |
Simplification to unit-less values gives the "1" as unit: |
| 107 |
```{r} |
| 108 |
m <- make_units(m) |
| 109 |
a * t / m |
| 110 |
``` |
| 111 |
|
| 112 |
Allowed operations that require convertible units are `+`, `-`, `==`, |
| 113 |
`!=`, `<`, `>`, `<=`, `>=`. Operations that lead to new units are |
| 114 |
`*`, `/`, and the power operations `**` and `^`. |
| 115 |
|
| 116 |
|
| 117 |
### Mathematical functions |
| 118 |
|
| 119 |
Mathematical operations allowed are: `abs`, `sign`, `floor`, |
| 120 |
`ceiling`, `trunc`, `round`, `signif`, `log`, `cumsum`, `cummax`, `cummin`. |
| 121 |
```{r} |
| 122 |
signif(a ** 2 / 3, 3) |
| 123 |
cumsum(a) |
| 124 |
log(a) # base defaults to exp(1) |
| 125 |
log(a, base = 10) |
| 126 |
log(a, base = 2) |
| 127 |
``` |
| 128 |
|
| 129 |
### Summary functions |
| 130 |
Summary functions `sum`, `min`, `max`, and `range` are allowed: |
| 131 |
```{r} |
| 132 |
sum(a) |
| 133 |
min(a) |
| 134 |
max(a) |
| 135 |
range(a) |
| 136 |
``` |
| 137 |
|
| 138 |
### Printing |
| 139 |
Following `difftime`, printing behaves differently for length-one vectors: |
| 140 |
```{r} |
| 141 |
a |
| 142 |
a[1] |
| 143 |
``` |
| 144 |
|
| 145 |
### Subsetting |
| 146 |
The usual subsetting rules work: |
| 147 |
```{r} |
| 148 |
a[2:5] |
| 149 |
a[-(1:9)] |
| 150 |
``` |
| 151 |
|
| 152 |
### Concatenation |
| 153 |
```{r} |
| 154 |
c(a,a) |
| 155 |
``` |
| 156 |
concatenation converts to the units of the first argument, if necessary: |
| 157 |
```{r} |
| 158 |
c(a,b) # m/s, km/h -> m/s |
| 159 |
c(b,a) # km/h, m/s -> km/h |
| 160 |
``` |
| 161 |
|
| 162 |
## Conversion to/from `difftime` |
| 163 |
From `difftime` to `units`: |
| 164 |
```{r} |
| 165 |
t1 = Sys.time() |
| 166 |
t2 = t1 + 3600 |
| 167 |
d = t2 - t1 |
| 168 |
(du = as_units(d)) |
| 169 |
``` |
| 170 |
vice versa: |
| 171 |
```{r} |
| 172 |
(dt = as_difftime(du)) |
| 173 |
class(dt) |
| 174 |
``` |
| 175 |
|
| 176 |
## units in `matrix` objects |
| 177 |
```{r} |
| 178 |
set_units(matrix(1:4,2,2), m/s) |
| 179 |
set_units(matrix(1:4,2,2), m/s * m/s) |
| 180 |
``` |
| 181 |
but |
| 182 |
```{r} |
| 183 |
set_units(matrix(1:4,2,2), m/s) %*% set_units(4:3, m/s) |
| 184 |
``` |
| 185 |
strips units. |
| 186 |
|
| 187 |
## units objects in `data.frame`s |
| 188 |
units in `data.frame` objects are printed, but do not appear in `summary`:. |
| 189 |
```{r} |
| 190 |
set.seed(131) |
| 191 |
d <- data.frame(x = runif(4), |
| 192 |
y = set_units(runif(4), s), |
| 193 |
z = set_units(1:4, m/s)) |
| 194 |
d |
| 195 |
summary(d) |
| 196 |
d$yz = with(d, y * z) |
| 197 |
d |
| 198 |
d[1, "yz"] |
| 199 |
``` |
| 200 |
## Formatting |
| 201 |
|
| 202 |
Units are often written in the form `m2 s-1`, for square meter per second. This |
| 203 |
can be defined as unit, and also parsed by `as_units`: |
| 204 |
```{r} |
| 205 |
(x = 1:10 * as_units("m2 s-1")) |
| 206 |
``` |
| 207 |
udunits understands such string, and can convert them |
| 208 |
```{r} |
| 209 |
y = 1:10 * make_units(m^2/s) |
| 210 |
x + y |
| 211 |
``` |
| 212 |
Printing units in this form is done by |
| 213 |
```{r} |
| 214 |
deparse_unit(x) |
| 215 |
``` |
| 216 |
|
| 217 |
## Plotting |
| 218 |
|
| 219 |
Base scatter plots and histograms support automatic unit placement |
| 220 |
in axis labels. In the following example we first convert to |
| 221 |
SI units. (Unit `in` needs a bit special treatment, because `in` is a |
| 222 |
reserved word in R.) |
| 223 |
|
| 224 |
```{r} |
| 225 |
mar = par("mar") + c(0, .3, 0, 0) |
| 226 |
displacement = mtcars$disp * as_units("in")^3 |
| 227 |
units(displacement) = make_units(cm^3) |
| 228 |
weight = mtcars$wt * 1000 * make_units(lb) |
| 229 |
units(weight) = make_units(kg) |
| 230 |
par(mar = mar) |
| 231 |
plot(weight, displacement) |
| 232 |
``` |
| 233 |
|
| 234 |
We can change grouping symbols from `[ ]` into `( )`: |
| 235 |
```{r} |
| 236 |
units_options(group = c("(", ")") ) # parenthesis instead of square brackets |
| 237 |
par(mar = mar) |
| 238 |
plot(weight, displacement) |
| 239 |
``` |
| 240 |
|
| 241 |
We can also remove grouping symbols, increase space between variable name and unit by: |
| 242 |
```{r} |
| 243 |
units_options(sep = c("~~~", "~"), group = c("", "")) # no brackets; extra space |
| 244 |
par(mar = mar) |
| 245 |
plot(weight, displacement) |
| 246 |
``` |
| 247 |
|
| 248 |
More complex units can be plotted either with negative powers, or as divisions, |
| 249 |
by modifying one of `units`'s global options using `units_options`: |
| 250 |
|
| 251 |
```{r} |
| 252 |
gallon = as_units("gallon") |
| 253 |
consumption = mtcars$mpg * make_units(mi/gallon) |
| 254 |
units(consumption) = make_units(km/l) |
| 255 |
par(mar = mar) |
| 256 |
plot(displacement, consumption) # division in consumption |
| 257 |
units_options(negative_power = TRUE) # division becomes ^-1 |
| 258 |
plot(displacement, consumption) # division in consumption |
| 259 |
``` |
| 260 |
|
| 261 |
As usual, units modify automatically in expressions: |
| 262 |
|
| 263 |
```{r} |
| 264 |
units_options(negative_power = TRUE) # division becomes ^-1 |
| 265 |
par(mar = mar) |
| 266 |
plot(displacement, consumption) |
| 267 |
plot(1/displacement, 1/consumption) |
| 268 |
``` |
| 269 |
|
| 270 |
```{r echo=FALSE} |
| 271 |
units_options(negative_power = FALSE) # division becomes / |
| 272 |
``` |