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 secsWe 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:
m/s is a valid physical unitm/s and km/h are convertibleThe 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.
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 sWe can set units to numerical values by set_units:
(a <- set_units(runif(10),  m/s))
## Units: m/s
##  [1] 0.3627074 0.4729954 0.3818758 0.7200037 0.4092184 0.6945217 0.9108062
##  [8] 0.8337860 0.1291454 0.3380821the result, e.g.
set_units(10, m/s)
## 10 m/sliterally 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)
## [1] 3225We can retrieve a single unit from the ud_units database by
with(ud_units, km/h)
## 1 km/hWhen 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
##  [1] 1.3057465 1.7027835 1.3747528 2.5920132 1.4731862 2.5002781 3.2789022
##  [8] 3.0016296 0.4649236 1.2170955Arithmetic operations verify units, and create new ones
a + a
## Units: m/s
##  [1] 0.7254147 0.9459908 0.7637515 1.4400073 0.8184368 1.3890434 1.8216123
##  [8] 1.6675720 0.2582909 0.6761642
a * a
## Units: m^2/s^2
##  [1] 0.13155663 0.22372467 0.14582910 0.51840529 0.16745970 0.48236037
##  [7] 0.82956785 0.69519912 0.01667855 0.11429949
a ^ 2
## Units: m^2/s^2
##  [1] 0.13155663 0.22372467 0.14582910 0.51840529 0.16745970 0.48236037
##  [7] 0.82956785 0.69519912 0.01667855 0.11429949
a ** -2
## Units: s^2/m^2
##  [1]  7.601290  4.469780  6.857342  1.928993  5.971586  2.073139  1.205447
##  [8]  1.438437 59.957261  8.748945and convert to the units of the first argument if necessary:
a + b # m/s + km/h -> m/s
## Units: m/s
##  [1] 0.7254147 0.9459908 0.7637515 1.4400073 0.8184368 1.3890434 1.8216123
##  [8] 1.6675720 0.2582909 0.6761642Currently, powers are only supported for integer powers, so using a ** 2.5 would result in an error.
There are some basic simplification of units:
t <- with(ud_units, s)
a * t
## Units: m
##  [1] 0.3627074 0.4729954 0.3818758 0.7200037 0.4092184 0.6945217 0.9108062
##  [8] 0.8337860 0.1291454 0.3380821which also work when units need to be converted before they can be simplified:
t <- with(ud_units, min)
a * t
## Units: m
##  [1] 21.762441 28.379725 22.912546 43.200220 24.553104 41.671301 54.648369
##  [8] 50.027161  7.748727 20.284925Simplification to unit-less values gives the “1” as unit:
m <- with(ud_units, m)
a * t / m
## Units: 1
##  [1] 21.762441 28.379725 22.912546 43.200220 24.553104 41.671301 54.648369
##  [8] 50.027161  7.748727 20.284925Allowed operations that require convertible units are +, -, ==, !=, <, >, <=, >=. Operations that lead to new units are *, /, and the power operations ** and ^.
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.04390 0.07460 0.04860 0.17300 0.05580 0.16100 0.27700 0.23200
##  [9] 0.00556 0.03810
cumsum(a)
## Units: m/s
##  [1] 0.3627074 0.8357028 1.2175785 1.9375822 2.3468006 3.0413223 3.9521285
##  [8] 4.7859145 4.9150599 5.2531420
log(a) # base defaults to exp(1)
## Units: (ln(m/s))
##  [1] -1.01415895 -0.74866957 -0.96265994 -0.32849897 -0.89350629
##  [6] -0.36453189 -0.09342519 -0.18177849 -2.04681600 -1.08446657
log(a, base = 10)
## Units: (lg(m/s))
##  [1] -0.44044364 -0.32514306 -0.41807790 -0.14266529 -0.38804485
##  [6] -0.15831419 -0.04057404 -0.07894539 -0.88892089 -0.47097785
log(a, base = 2)
## Units: (lb(m/s))
##  [1] -1.4631221 -1.0801019 -1.3888247 -0.4739238 -1.2890571 -0.5259084
##  [7] -0.1347841 -0.2622509 -2.9529313 -1.5645545Summary functions sum, min, max, and range are allowed:
sum(a)
## 5.253142 m/s
min(a)
## 0.1291454 m/s
max(a)
## 0.9108062 m/s
range(a)
## Units: m/s
## [1] 0.1291454 0.9108062
with(ud_units, min(m/s, km/h)) # converts to first unit:
## 0.2777778 m/sFollowing difftime, printing behaves differently for length-one vectors:
a
## Units: m/s
##  [1] 0.3627074 0.4729954 0.3818758 0.7200037 0.4092184 0.6945217 0.9108062
##  [8] 0.8337860 0.1291454 0.3380821
a[1]
## 0.3627074 m/sThe usual subsetting rules work:
a[2:5]
## Units: m/s
## [1] 0.4729954 0.3818758 0.7200037 0.4092184
a[-(1:9)]
## 0.3380821 m/sc(a,a)
## Units: m/s
##  [1] 0.3627074 0.4729954 0.3818758 0.7200037 0.4092184 0.6945217 0.9108062
##  [8] 0.8337860 0.1291454 0.3380821 0.3627074 0.4729954 0.3818758 0.7200037
## [15] 0.4092184 0.6945217 0.9108062 0.8337860 0.1291454 0.3380821concatenation converts to the units of the first argument, if necessary:
c(a,b) # m/s, km/h -> m/s
## Units: m/s
##  [1] 0.3627074 0.4729954 0.3818758 0.7200037 0.4092184 0.6945217 0.9108062
##  [8] 0.8337860 0.1291454 0.3380821 0.3627074 0.4729954 0.3818758 0.7200037
## [15] 0.4092184 0.6945217 0.9108062 0.8337860 0.1291454 0.3380821
c(b,a) # km/h, m/s -> km/h
## Units: km/h
##  [1] 1.3057465 1.7027835 1.3747528 2.5920132 1.4731862 2.5002781 3.2789022
##  [8] 3.0016296 0.4649236 1.2170955 1.3057465 1.7027835 1.3747528 2.5920132
## [15] 1.4731862 2.5002781 3.2789022 3.0016296 0.4649236 1.2170955difftimeFrom difftime to units:
t1 = Sys.time() 
t2 = t1 + 3600 
d = t2 - t1
(du = as_units(d))
## 1 hvice versa:
(dt = as_difftime(du))
## Time difference of 1 hours
class(dt)
## [1] "difftime"matrix objectsset_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    4but
set_units(matrix(1:4,2,2), m/s) %*% set_units(4:3, m/s)
## Units: m^2/s^2
##      [,1]
## [1,]   13
## [2,]   20strips units.
data.framesunits 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 mUnits 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 10udunits understands such string, and can convert them
y = 1:10 * with(ud_units, m^2/s)
x + y
## Units: m^2/s
##  [1]  2  4  6  8 10 12 14 16 18 20Printing units in this form is done by
deparse_unit(x)
## [1] "m2 s-1"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 consumptionunits_options(negative_power = TRUE) # division becomes ^-1
plot(displacement, consumption) # division in consumptionAs 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)