Units of Measurement for R Vectors: an Introduction

R has little support for physical measurement units. The exception is formed by time differences: time differences objects of class difftime have a units attribute that can be modified:

t1 = Sys.time() 
t2 = t1 + 3600 
d = t2 - t1
class(d)
## [1] "difftime"
units(d)
## [1] "hours"
d
## Time difference of 1 hours
units(d) = "secs"
d
## Time difference of 3600 secs

We see here that the units method is used to retrieve and modify the unit of time differences.

The units package generalizes this idea to other physical units, building upon the udunits2 C library. The udunits2 library provides the following operations:

  • validating whether an expression, such as m/s is a valid physical unit
  • verifying whether two units such as m/s and km/h are convertible
  • converting values between two convertible units
  • providing names and symbols for specific units
  • handle different character encodings (utf8, ascii, iso-8859-1 and latin1)

The units R package uses the udunits2 C library to extend R with functionality for manipulating numeric vectors that have physical measurement units associated with them, in a similar way as difftime objects behave.

Setting units, unit conversion

We can set units to numerical values by set_units:

library(units)
(a <- set_units(runif(10),  m/s))
## Units: [m/s]
##  [1] 0.02439215 0.48012761 0.02654962 0.36049046 0.25777921 0.79431508
##  [7] 0.18436444 0.58351676 0.51852513 0.62324241

the result, e.g. 

set_units(10, m/s)
## 10 [m/s]

literally means “10 times 1 m divided by 1 s”. In writing, the “1” values are omitted, and the multiplication is implicit.

Unit conversion

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

b = a
units(b) <- make_units(km/h)
b
## Units: [km/h]
##  [1] 0.08781173 1.72845939 0.09557864 1.29776567 0.92800517 2.85953428
##  [7] 0.66371197 2.10066033 1.86669047 2.24367268

Basic manipulations

Arithmetic operations

Arithmetic operations verify units, and create new ones

a + a
## Units: [m/s]
##  [1] 0.04878429 0.96025522 0.05309924 0.72098093 0.51555843 1.58863016
##  [7] 0.36872887 1.16703352 1.03705026 1.24648482
a * a
## Units: [m^2/s^2]
##  [1] 0.0005949768 0.2305225215 0.0007048824 0.1299533741 0.0664501226
##  [6] 0.6309364440 0.0339902455 0.3404918065 0.2688683123 0.3884311044
a ^ 2
## Units: [m^2/s^2]
##  [1] 0.0005949768 0.2305225215 0.0007048824 0.1299533741 0.0664501226
##  [6] 0.6309364440 0.0339902455 0.3404918065 0.2688683123 0.3884311044
a ** -2
## Units: [s^2/m^2]
##  [1] 1680.737757    4.337971 1418.676312    7.695068   15.048881    1.584946
##  [7]   29.420205    2.936928    3.719293    2.574459

and convert to the units of the first argument if necessary:

a + b # m/s + km/h -> m/s
## Units: [m/s]
##  [1] 0.04878429 0.96025522 0.05309924 0.72098093 0.51555843 1.58863016
##  [7] 0.36872887 1.16703352 1.03705026 1.24648482

Currently, powers are only supported for integer powers, so using a ** 2.5 would result in an error.

Unit simplification

There are some basic simplification of units:

t <- make_units(s)
a * t
## Units: [m]
##  [1] 0.02439215 0.48012761 0.02654962 0.36049046 0.25777921 0.79431508
##  [7] 0.18436444 0.58351676 0.51852513 0.62324241

which also work when units need to be converted before they can be simplified:

t <- make_units(min)
a * t
## Units: [m]
##  [1]  1.463529 28.807657  1.592977 21.629428 15.466753 47.658905 11.061866
##  [8] 35.011005 31.111508 37.394545

Simplification to unit-less values gives the “1” as unit:

m <- make_units(m)
a * t / m
## Units: [1]
##  [1]  1.463529 28.807657  1.592977 21.629428 15.466753 47.658905 11.061866
##  [8] 35.011005 31.111508 37.394545

Allowed operations that require convertible units are +, -, ==, !=, <, >, <=, >=. Operations that lead to new units are *, /, and the power operations ** and ^.

Mathematical functions

Mathematical operations allowed are: abs, sign, floor, ceiling, trunc, round, signif, log, cumsum, cummax, cummin.

signif(a ** 2 / 3, 3)
## Units: [m^2/s^2]
##  [1] 0.000198 0.076800 0.000235 0.043300 0.022200 0.210000 0.011300 0.113000
##  [9] 0.089600 0.129000
cumsum(a)
## Units: [m/s]
##  [1] 0.02439215 0.50451976 0.53106938 0.89155984 1.14933905 1.94365413
##  [7] 2.12801857 2.71153533 3.23006046 3.85330287
log(a) # base defaults to exp(1)
## Units: [(ln(re 1 m.s-1))]
##  [1] -3.7134941 -0.7337034 -3.6287398 -1.0202898 -1.3556518 -0.2302751
##  [7] -1.6908408 -0.5386821 -0.6567668 -0.4728197
log(a, base = 10)
## Units: [(lg(re 1 m.s-1))]
##  [1] -1.6127500 -0.3186433 -1.5759417 -0.4431062 -0.5887521 -0.1000072
##  [7] -0.7343228 -0.2339467 -0.2852302 -0.2053430
log(a, base = 2)
## Units: [(lb(re 1 m.s-1))]
##  [1] -5.3574395 -1.0585102 -5.2351649 -1.4719670 -1.9557922 -0.3322167
##  [7] -2.4393677 -0.7771540 -0.9475142 -0.6821347

Summary functions

Summary functions sum, min, max, and range are allowed:

sum(a)
## 3.853303 [m/s]
min(a)
## 0.02439215 [m/s]
max(a)
## 0.7943151 [m/s]
range(a)
## Units: [m/s]
## [1] 0.02439215 0.79431508
make_units(min(m/s, km/h)) # converts to first unit:
## 0.2777778 [m/s]

Printing

Following difftime, printing behaves differently for length-one vectors:

a
## Units: [m/s]
##  [1] 0.02439215 0.48012761 0.02654962 0.36049046 0.25777921 0.79431508
##  [7] 0.18436444 0.58351676 0.51852513 0.62324241
a[1]
## 0.02439215 [m/s]

Subsetting

The usual subsetting rules work:

a[2:5]
## Units: [m/s]
## [1] 0.48012761 0.02654962 0.36049046 0.25777921
a[-(1:9)]
## 0.6232424 [m/s]

Concatenation

c(a,a)
## Units: [m/s]
##  [1] 0.02439215 0.48012761 0.02654962 0.36049046 0.25777921 0.79431508
##  [7] 0.18436444 0.58351676 0.51852513 0.62324241 0.02439215 0.48012761
## [13] 0.02654962 0.36049046 0.25777921 0.79431508 0.18436444 0.58351676
## [19] 0.51852513 0.62324241

concatenation converts to the units of the first argument, if necessary:

c(a,b) # m/s, km/h -> m/s
## Units: [m/s]
##  [1] 0.02439215 0.48012761 0.02654962 0.36049046 0.25777921 0.79431508
##  [7] 0.18436444 0.58351676 0.51852513 0.62324241 0.02439215 0.48012761
## [13] 0.02654962 0.36049046 0.25777921 0.79431508 0.18436444 0.58351676
## [19] 0.51852513 0.62324241
c(b,a) # km/h, m/s -> km/h
## Units: [km/h]
##  [1] 0.08781173 1.72845939 0.09557864 1.29776567 0.92800517 2.85953428
##  [7] 0.66371197 2.10066033 1.86669047 2.24367268 0.08781173 1.72845939
## [13] 0.09557864 1.29776567 0.92800517 2.85953428 0.66371197 2.10066033
## [19] 1.86669047 2.24367268

Conversion to/from difftime

From difftime to units:

t1 = Sys.time() 
t2 = t1 + 3600 
d = t2 - t1
(du = as_units(d))
## 1 [h]

vice versa:

(dt = as_difftime(du))
## Time difference of 1 hours
class(dt)
## [1] "difftime"

units in matrix objects

set_units(matrix(1:4,2,2), m/s)
## Units: [m/s]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
set_units(matrix(1:4,2,2), m/s * m/s)
## Units: [m^2/s^2]
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4

but

set_units(matrix(1:4,2,2), m/s) %*% set_units(4:3, m/s)
##      [,1]
## [1,]   13
## [2,]   20

strips units.

units objects in data.frames

units in data.frame objects are printed, but do not appear in summary:.

set.seed(131)
d <- data.frame(x = runif(4), 
                    y = set_units(runif(4), s), 
                    z = set_units(1:4, m/s))
d
##           x             y       z
## 1 0.2064370 0.8463468 [s] 1 [m/s]
## 2 0.1249422 0.5292048 [s] 2 [m/s]
## 3 0.2932732 0.5186254 [s] 3 [m/s]
## 4 0.3757797 0.2378545 [s] 4 [m/s]
summary(d)
##        x                y                z       
##  Min.   :0.1249   Min.   :0.2379   Min.   :1.00  
##  1st Qu.:0.1861   1st Qu.:0.4484   1st Qu.:1.75  
##  Median :0.2499   Median :0.5239   Median :2.50  
##  Mean   :0.2501   Mean   :0.5330   Mean   :2.50  
##  3rd Qu.:0.3139   3rd Qu.:0.6085   3rd Qu.:3.25  
##  Max.   :0.3758   Max.   :0.8463   Max.   :4.00
d$yz = with(d, y * z)
d
##           x             y       z            yz
## 1 0.2064370 0.8463468 [s] 1 [m/s] 0.8463468 [m]
## 2 0.1249422 0.5292048 [s] 2 [m/s] 1.0584095 [m]
## 3 0.2932732 0.5186254 [s] 3 [m/s] 1.5558761 [m]
## 4 0.3757797 0.2378545 [s] 4 [m/s] 0.9514180 [m]
d[1, "yz"]
## 0.8463468 [m]

Formatting

Units are often written in the form m2 s-1, for square meter per second. This can be defined as unit, and also parsed by as_units:

(x = 1:10 * as_units("m2 s-1"))
## Units: [m^2/s]
##  [1]  1  2  3  4  5  6  7  8  9 10

udunits understands such string, and can convert them

y = 1:10 * make_units(m^2/s)
x + y
## Units: [m^2/s]
##  [1]  2  4  6  8 10 12 14 16 18 20

Printing units in this form is done by

deparse_unit(x)
## [1] "m2 s-1"

Plotting

Base scatter plots and histograms support automatic unit placement in axis labels. In the following example we first convert to SI units. (Unit in needs a bit special treatment, because in is a reserved word in R.)

mar = par("mar") + c(0, .3, 0, 0)
displacement = mtcars$disp * as_units("in")^3
units(displacement) = make_units(cm^3)
weight = mtcars$wt * 1000 * make_units(lb)
units(weight) = make_units(kg)
par(mar = mar)
plot(weight, displacement)

We can change grouping symbols from [ ] into ( ):

units_options(group = c("(", ")") )  # parenthesis instead of square brackets
par(mar = mar)
plot(weight, displacement)

We can also remove grouping symbols, increase space between variable name and unit by:

units_options(sep = c("~~~", "~"), group = c("", ""))  # no brackets; extra space
par(mar = mar)
plot(weight, displacement)

More complex units can be plotted either with negative powers, or as divisions, by modifying one of units’s global options using units_options:

gallon = as_units("gallon")
consumption = mtcars$mpg * make_units(mi/gallon)
units(consumption) = make_units(km/l)
par(mar = mar)
plot(displacement, consumption) # division in consumption

units_options(negative_power = TRUE) # division becomes ^-1
plot(displacement, consumption) # division in consumption

As usual, units modify automatically in expressions:

units_options(negative_power = TRUE) # division becomes ^-1
par(mar = mar)
plot(displacement, consumption)

plot(1/displacement, 1/consumption)