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)
##  "difftime"
units(d)
##  "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 R package, which in turn is build 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 R package udunits2 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

Existing units are resolved from a database in the units package, called ud_units. We can see the first three elements of it by

library(units)
ud_units[1:3]
## $m ## 1 m ## ##$kg
## 1 kg
##
## $s ## 1 s We can set units to numerical values by set_units: (a <- set_units(runif(10), m/s)) ## Units: m/s ##  0.597066148 0.409161287 0.125693897 0.165898255 0.005796453 ##  0.293256568 0.575769936 0.413805027 0.754264704 0.749672955 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. The units package comes with a list of over 3000 predefined units, length(ud_units) ##  3225 We can retrieve a single unit from the ud_units database by with(ud_units, km/h) ## 1 km/h ### 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) <- with(ud_units, km/h) b ## Units: km/h ##  2.14943813 1.47298063 0.45249803 0.59723372 0.02086723 1.05572365 ##  2.07277177 1.48969810 2.71535293 2.69882264 ## Basic manipulations ### Arithmetic operations Arithmetic operations verify units, and create new ones a + a ## Units: m/s ##  1.19413230 0.81832257 0.25138779 0.33179651 0.01159291 0.58651314 ##  1.15153987 0.82761005 1.50852941 1.49934591 a * a ## Units: m^2/s^2 ##  3.564880e-01 1.674130e-01 1.579896e-02 2.752223e-02 3.359887e-05 ##  8.599941e-02 3.315110e-01 1.712346e-01 5.689152e-01 5.620095e-01 a ^ 2 ## Units: m^2/s^2 ##  3.564880e-01 1.674130e-01 1.579896e-02 2.752223e-02 3.359887e-05 ##  8.599941e-02 3.315110e-01 1.712346e-01 5.689152e-01 5.620095e-01 a ** -2 ## Units: s^2/m^2 ##  2.805144 5.973253 63.295323 36.334264 29762.903417 ##  11.627986 3.016491 5.839941 1.757731 1.779329 and convert to the units of the first argument if necessary: a + b # m/s + km/h -> m/s ## Units: m/s ##  1.19413230 0.81832257 0.25138779 0.33179651 0.01159291 0.58651314 ##  1.15153987 0.82761005 1.50852941 1.49934591 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 <- with(ud_units, s) a * t ## Units: m ##  0.597066148 0.409161287 0.125693897 0.165898255 0.005796453 ##  0.293256568 0.575769936 0.413805027 0.754264704 0.749672955 which also work when units need to be converted before they can be simplified: t <- with(ud_units, min) a * t ## Units: m ##  35.8239689 24.5496772 7.5416338 9.9538953 0.3477872 17.5953941 ##  34.5461962 24.8283016 45.2558822 44.9803773 Simplification to unit-less values gives the “1” as unit: m <- with(ud_units, m) a * t / m ## Units: 1 ##  35.8239689 24.5496772 7.5416338 9.9538953 0.3477872 17.5953941 ##  34.5461962 24.8283016 45.2558822 44.9803773 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.19e-01 5.58e-02 5.27e-03 9.17e-03 1.12e-05 2.87e-02 1.11e-01 ##  5.71e-02 1.90e-01 1.87e-01 cumsum(a) ## Units: m/s ##  0.5970661 1.0062274 1.1319213 1.2978196 1.3036160 1.5968726 2.1726425 ##  2.5864476 3.3407123 4.0903852 log(a) # base defaults to exp(1) ## Units: (ln(m/s)) ##  -0.5157274 -0.8936459 -2.0739057 -1.7963806 -5.1505090 -1.2267074 ##  -0.5520471 -0.8823604 -0.2820119 -0.2881182 log(a, base = 10) ## Units: (lg(m/s)) ##  -0.2239776 -0.3881055 -0.9006858 -0.7801582 -2.2368376 -0.5327523 ##  -0.2397510 -0.3832042 -0.1224762 -0.1251282 log(a, base = 2) ## Units: (lb(m/s)) ##  -0.7440373 -1.2892584 -2.9920135 -2.5916294 -7.4306138 -1.7697647 ##  -0.7964356 -1.2729769 -0.4068572 -0.4156667 ### Summary functions Summary functions sum, min, max, and range are allowed: sum(a) ## 4.090385 m/s min(a) ## 0.005796453 m/s max(a) ## 0.7542647 m/s range(a) ## Units: m/s ##  0.005796453 0.754264704 with(ud_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 ##  0.597066148 0.409161287 0.125693897 0.165898255 0.005796453 ##  0.293256568 0.575769936 0.413805027 0.754264704 0.749672955 a ## 0.5970661 m/s ### Subsetting The usual subsetting rules work: a[2:5] ## Units: m/s ##  0.409161287 0.125693897 0.165898255 0.005796453 a[-(1:9)] ## 0.749673 m/s ### Concatenation c(a,a) ## Units: m/s ##  0.597066148 0.409161287 0.125693897 0.165898255 0.005796453 ##  0.293256568 0.575769936 0.413805027 0.754264704 0.749672955 ##  0.597066148 0.409161287 0.125693897 0.165898255 0.005796453 ##  0.293256568 0.575769936 0.413805027 0.754264704 0.749672955 concatenation converts to the units of the first argument, if necessary: c(a,b) # m/s, km/h -> m/s ## Units: m/s ##  0.597066148 0.409161287 0.125693897 0.165898255 0.005796453 ##  0.293256568 0.575769936 0.413805027 0.754264704 0.749672955 ##  0.597066148 0.409161287 0.125693897 0.165898255 0.005796453 ##  0.293256568 0.575769936 0.413805027 0.754264704 0.749672955 c(b,a) # km/h, m/s -> km/h ## Units: km/h ##  2.14943813 1.47298063 0.45249803 0.59723372 0.02086723 1.05572365 ##  2.07277177 1.48969810 2.71535293 2.69882264 2.14943813 1.47298063 ##  0.45249803 0.59723372 0.02086723 1.05572365 2.07277177 1.48969810 ##  2.71535293 2.69882264 ## 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) ##  "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  2  3  4  5  6  7  8  9 10

udunits understands such string, and can convert them

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

Printing units in this form is done by

deparse_unit(x)
##  "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 * ud_units[["in"]]^3 units(displacement) = with(ud_units, cm^3) weight = mtcars$wt * 1000 * with(ud_units, lb)
units(weight) = with(ud_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 * with(ud_units, mi/gallon)
units(consumption) = with(ud_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) 