Units & Metric Scaling

All chemical quantities in this package keep track of the units they represent with a base unit as detailed in the quantities vignette and a metric prefix. By default, the metric prefix is adjusted automatically to keep numeric values in a range close to 1. However, scaling to a specific prefix is easily achieved.

# automatic scaling
qty(5000, "g") %>% print() # automatically scaled to kg
## Mass [kg]
## [1] 5
qty(5000, "g", scale_to_best_metric = FALSE) %>% print() # stays g
## Mass [g]
## [1] 5000
# specific scaling
qty(100, "mg") %>% base_metric() %>% print() # scale to the base unit (here g)
## Mass [g]
## [1] 0.1
qty(100, "mM") %>% base_metric() %>% print() # scale to the base unit (here M)
## Molarity [M]
## [1] 0.1
qty(100, "mg") %>% scale_metric("k") %>% print()
## Mass [kg]
## [1] 1e-04

The actual numeric value of a quantity can be retrieved via the get_qty_value() function which takes an optional parameter to specify which unit the value should be retrieved in (by default it is the unit that the quantity is currently in). Additionally, a transformation function can be specified for easy log or other transformations.

qty(100, "mg") %>% get_qty_value() # returns 100
## [1] 100
qty(0.1, "g") %>% get_qty_value() # returns 100 because the units are "mg"
## [1] 100
qty(0.1, "g") %>% get_qty_value("g") # better to be specific upon retrieval
## [1] 0.1
qty(0.1, "g") %>% get_qty_value("g", log10) # applies a log10 transform
## [1] -1
qty(0.1, "g") %>% get_qty_value("kg") # can use any valid unit
## [1] 1e-04
qty(0.1, "g") %>% get_qty_value("kg", sqrt) # and any transformation
## [1] 0.01
qty(0, "C") %>% get_qty_value("F") # or use it for unit conversion
## [1] 32
qty(760, "Torr") %>% get_qty_value("atm") # or use it for unit conversion
## [1] 1

To retrieven numeric values as text that includes their units, simply use get_qty_text() instead of get_qty_value().

## [1] "100 mg"
qty(0:10, "C") %>% get_qty_text("F")
##  [1] "32 F"   "33.8 F" "35.6 F" "37.4 F" "39.2 F" "41 F"   "42.8 F"
##  [8] "44.6 F" "46.4 F" "48.2 F" "50 F"
qty(760, "Torr") %>% get_qty_text("atm")
## [1] "1 atm"

To include this type of quantity text in axis tickmark labels, color/shape/linetype scale labels or facet labels, generate a labeller function using make_qty_text_labeller() and use it as the labels parameter for scales or the labeller parameter for facets.

## [1] "100 mg" "1 g"    "1 kg"
## [1] "0.1 g"  "1 g"    "1000 g"

The units of a quantity object can also be retrieved directly with the get_qty_units() function for a single quantity, list of quantities as well as entire data frames (see details on the latter in the data frames section).

qty(5000, "g") %>% get_qty_units()
## [1] "kg"
x <- list(
  a = qty(5000, "g"),
  b = 42,
  c = qty(100, "mbar")
) 
x %>% get_qty_units() %>% print()
##      a      b      c 
##   "kg"     NA "mbar"

For easy construction of plot axis or legend labels, the function get_qty_units_with_label() further provides an easy way to combine labels with the units. By default (for lists and data frames), it uses the names of the list variable/data frame columns (see details on the latter in the data frames section).

qty(5000, "g") %>% get_qty_units_with_label("weight")
## [1] "weight [kg]"
##          a          b          c 
##   "a [kg]"        "b" "c [mbar]"
x %>% get_qty_units_with_label("same label") %>% print()
##                   a                   b                   c 
##   "same label [kg]"        "same label" "same label [mbar]"
x %>% get_qty_units_with_label(c("apple", "banana", "carrot")) %>% print()
##               a               b               c 
##    "apple [kg]"        "banana" "carrot [mbar]"

Arithmetic

Several common arithmetic operations are implemented for easy interconversion between quantities. All arithmetic operations also automatically keep track of the units and metric prefixes for correct calculations.

Addition and Subtraction

Quantities of the same type (e.g. masses, volumes, etc.) can be added or subtracted with proper interpration of the metric prefixes. The resulting quantity will be scaled to the best metric prefix as described above. Attempts to add or subtract non-matching quantities (e.g. mass + volume) or a quantity and a number without units will fail with an error to avoid unexpect behaviour and ambiguous calculations.

print(qty(0.003, "g") - qty(2, "mg") + qty(5, "µg")) # 1.005 mg
## Mass [mg]
## [1] 1.005
try(qty(1, "g") + qty(1, "L")) # not allowed
## Error : addition is not implemented for these quantities (trying to use 'MediaChemToolsMass' and 'MediaChemToolsVolume').
try(qty(1, "g") + 1) # not allowed
## Error : addition is not implemented for these quantities (trying to use 'MediaChemToolsMass' and 'numeric').

Multiplication / Division

Quantities can be multipled/divided by a number. The resulting quantity will be scaled to the best metric prefix. This is most commonly used with multiplication/division by 1000.

print(qty(1, "mg") * 1000) # convert mg into g
## Mass [g]
## [1] 1
print(qty(1, "mg") / 1e6) # convert mg into ng
## Mass [ng]
## [1] 1

Quantities can also be divided by another quantity of the same type (e.g. a mass by another mass) effectively canceling out the units resulting in a regular number (with the metric prefixes properly taken into consideration).

# how many mg in a kg?
qty(1, "mg") / qty(1, "kg")
## [1] 1e-06

Additional multiplications and divisions are possible for specific combinations of quantities as detailed below. These formulas are each implemented for all three possible arrangements.

Molarity = Amount / Volume

print(qty(5, "nmol") / qty(50, "mL")) # calculation molarity
## Molarity [nM]
## [1] 100
print(qty(5, "nmol") / qty(100, "nM")) # calculate volume
## Volume [mL]
## [1] 50
print(qty(100, "nM") * qty(50, "mL")) # calculate amount
## Amount [nmol]
## [1] 5

Density = Mass / Volume

print(qty(5, "ng") / qty(50, "mL")) # calculate density
## Density [ng/L]
## [1] 100
print(qty(5, "ng") / qty(100, "ng/L")) # calculate volume
## Volume [mL]
## [1] 50
print(qty(100, "ng/L") * qty(50, "mL")) # calculate mass
## Mass [ng]
## [1] 5

Amount = Mass / Molecular Mass

print(qty(10, "g") / qty (50, "g/mol")) # calculate amount
## Amount [mmol]
## [1] 200
print(qty(10, "g") / qty(200, "mmol")) # calculate molecular mass
## MolecularMass [g/mol]
## [1] 50
print(qty(200, "mmol") * qty (50, "g/mol")) # calculate mass
## Mass [g]
## [1] 10

Solubility = Molarity / Pressure

print(qty(10, "mM") / qty(200, "mbar")) # calculate solubility
## Solubility [mM/bar]
## [1] 50
print(qty(10, "mM") / qty(50, "mM/bar")) # calculate pressure
## Pressure [mbar]
## [1] 200
print(qty(50, "mM/bar") * qty (200, "mbar")) # calculate molarity
## Molarity [mM]
## [1] 10

Comparisons

Quantities can be compared with all common logic operators (>, >=, <, <=, ==, !=) taking the metric scaling properly into consideration. Attempts to compare non-matching quantities (e.g. mass & volume) will fail with an error to avoid unexpect behaviour. Comparisons of quantities with numerics are allowed but it is important to be cautious about these since the metric scaling in quantities affects the numeric value.

qty(5, "mg") < qty(1, "g")
## [1] TRUE
qty(5, "mg") > qty(10, "ng")
## [1] TRUE
qty(5, "mg") == qty(0.005, "g")
## [1] TRUE
qty(5, "mg") != qty(5, "g")
## [1] TRUE
try(qty(1, "mg") > qty(1, "L")) # not allowed (different quantities)
## Error : comparison is not implemented for these quantities (trying to use 'MediaChemToolsMass' and 'MediaChemToolsVolume').
qty(1, "mg") == 1 # allowed but important to be careful
## [1] TRUE
qty(0.1, "g") == 0.1 # example of metric scaling affecting the comparison
## [1] FALSE
qty(0.1, "g") == 100 # example of metric scaling affecting the comparison
## [1] TRUE

It is important to note that due to machine errors, the == is best avoided in favor of more reliable comparisions such as tests that check whether the difference between quantities is smaller than a tiny quantity:

(x <- qty(1, "mg"))
## Mass [mg]
## [1] 1
## Mass [µg]
## [1] 333.3333
## Mass [mg]
## [1] 1
## [1] FALSE
abs(x - x2) < qty(1, "fg") # absolute difference smaller than 1 femtogram
## [1] TRUE

Data Frames

Quantities are fully supported in dplyr type data frames and the units of a quantity are displayed underneath the column headers, e.g. <mg> to indicate a quantity column that has the units of mg (and thus is a mass).

## # A tibble: 5 x 2
##   weight volume
##   <mg>   <mL>  
## 1 1      20    
## 2 2      20    
## 3 3      20    
## 4 4      20    
## 5 5      20

This also means that all common arithmetic operations are allowed within data frames.

## # A tibble: 5 x 8
##   weight vol   mw      amount conc  new_vol new_weight `correct?`
##   <mg>   <mL>  <g/mol> <µmol> <µM>  <L>     <mg>       <lgl>     
## 1 1      20    500      2     100   1        50        TRUE      
## 2 2      20    500      4     200   1       100        TRUE      
## 3 3      20    500      6     300   1       150        TRUE      
## 4 4      20    500      8     400   1       200        TRUE      
## 5 5      20    500     10     500   1       250        TRUE

To get the quantities’ units or full labels, simply use get_qty_units() and get_qty_units_with_label()

df %>% get_qty_units() %>% print()
##     weight        vol         mw     amount       conc    new_vol 
##       "mg"       "mL"    "g/mol"     "µmol"       "µM"        "L" 
## new_weight   correct? 
##       "mg"         NA
##            weight               vol                mw            amount 
##     "weight [mg]"        "vol [mL]"      "mw [g/mol]"   "amount [µmol]" 
##              conc           new_vol        new_weight          correct? 
##       "conc [µM]"     "new_vol [L]" "new_weight [mg]"        "correct?"

Concatenation

Quantities can be concatenated using the regular c() function (or the more explicit c_qty()) as long as they are the same type of quantity (e.g. all masses). Concatenation make sure that the metric prefix is taken into consideration and scales the new vector to the best metric of the median.

c(
  qty(1, "g"), 
  qty(1:3, "mg"),
  qty(2, "g")
) %>% print()
## Mass [mg]
## [1] 1000    1    2    3 2000

Missing data

Missing data (NA), empty vector (numeric(0)) and infinity placeholders (Inf, -Inf) are supported in all quantities and work the same as in any other R vectors.

qty(NA, "mg") %>% print()
## Mass [g]
## [1] NA
qty(Inf, "mg") %>% print()
## Mass [g]
## [1] Inf
qty(numeric(0), "mg") %>% print()
## Mass [g]
## numeric(0)
qty(c(10, NA, -Inf, Inf, numeric(0)), "mg") %>% print()
## Mass [mg]
## [1]   10   NA -Inf  Inf

Miscellaneous

To check whether something is a quantity, use the is_qty() function.

qty(1, "mg") %>% is_qty() # is a quantity
## [1] TRUE
1 %>% is_qty() # not a quantity
## [1] FALSE