| Version: | 1.0-0 |
| Title: | Measurement Units for R Vectors |
| Depends: | R (≥ 3.5.0) |
| Imports: | Rcpp |
| LinkingTo: | Rcpp (≥ 0.12.10) |
| Suggests: | NISTunits, measurements, xml2, magrittr, pillar (≥ 1.3.0),dplyr (≥ 1.0.0), vctrs (≥ 0.3.1), ggplot2 (> 3.2.1), testthat(≥ 3.0.0), vdiffr, knitr, rvest, rmarkdown |
| VignetteBuilder: | knitr |
| Description: | Support for measurement units in R vectors, matrices and arrays: automatic propagation, conversion, derivation and simplification of units; raising errors in case of unit incompatibility. Compatible with the POSIXct, Date and difftime classes. Uses the UNIDATA udunits library and unit database for unit compatibility checking and conversion. Documentation about 'units' is provided in the paper by Pebesma, Mailund & Hiebert (2016, <doi:10.32614/RJ-2016-061>), included in this package as a vignette; see 'citation("units")' for details. |
| SystemRequirements: | udunits-2 |
| License: | GPL-2 |
| URL: | https://r-quantities.github.io/units/,https://github.com/r-quantities/units |
| BugReports: | https://github.com/r-quantities/units/issues |
| RoxygenNote: | 7.3.3 |
| Encoding: | UTF-8 |
| Config/testthat/edition: | 3 |
| NeedsCompilation: | yes |
| Packaged: | 2025-10-05 19:45:48 UTC; edzer |
| Author: | Edzer Pebesma |
| Maintainer: | Edzer Pebesma <edzer.pebesma@uni-muenster.de> |
| Repository: | CRAN |
| Date/Publication: | 2025-10-09 10:40:02 UTC |
Mathematical operations for units objects
Description
Mathematical operations for units objects
Usage
## S3 method for class 'units'Math(x, ...)Arguments
x | object of class units |
... | parameters passed on to the Math functions |
Details
Logarithms receive a special treatment by the underlyingudunits2library. If a natural logarithm is applied to someunit, the result isln(re 1 unit), which meansnatural logarithm referenced to1 unit. For base 2 and base 10 logarithms, the outputlb(...)andlg(...) respectively instead ofln(...).
This is particularly important for some units that are typically expressed ina logarithmic scale (i.e.,bels, or, more commonly,decibels),such as Watts or Volts. For some of these units, the defaultudunits2database contains aliases: e.g.,BW (bel-Watts) is an alias oflg(re 1 W);Bm (bel-milliWatts) is an alias oflg(re 0.001 W);BV is an alias oflg(re 1 V) (bel-Volts),and so on and so forth (see the output ofvalid_udunits() for furtherreference).
Additionally, theunits package definesB, thebel, bydefault (because it is not defined byudunits2) as an alias oflg(re 1), unless a user-provided XML database already contains adefinition ofB, or thedefine_bel option is set toFALSE(seehelp(units_options)).
Examples
# roundings, cummulative functionsx <- set_units(sqrt(1:10), m/s)signif(x, 2)cumsum(x)# trigonometrysin(x) # not meaningfulx <- set_units(sqrt(1:10), rad)sin(x)cos(x)x <- set_units(seq(0, 1, 0.1), 1)asin(x)acos(x)# logarithmsx <- set_units(sqrt(1:10), W)log(x) # base exp(1)log(x, base = 3)log2(x)log10(x)set_units(x, dBW) # decibel-wattsset_units(x, dBm) # decibel-milliwattsS3 Ops Group Generic Functions for units objects
Description
Ops functions for units objects, including comparison, product and divide,add, subtract.
Usage
## S3 method for class 'units'Ops(e1, e2)Arguments
e1 | object of class |
e2 | object of class |
Details
Users are advised against performing arithmetical operations withtemperatures in different units. Theunits package ensure that results1) are arithmetically correct, and 2) satisfy dimensional analysis, but couldnever ensure that results are physically meaningful. Temperature units arespecial because there is an absolute unit, Kelvin, and relative ones, Celsiusand Fahrenheit degrees. Arithmetic operations between them are meaninglessfrom the physical standpoint. Users are thus advised to convert alltemperatures to Kelvin before operating.
Value
object of classunits
Examples
a <- set_units(1:3, m/s)b <- set_units(1:3, m/s)a + ba * ba / ba <- as_units("kg m-3")b <- set_units(1, kg/m/m/m)a + ba = set_units(1:5, m)a %/% aa %/% set_units(2)set_units(1:5, m^2) %/% set_units(2, m)a %% aa %% set_units(2)convert units object into difftime object
Description
convert units object into difftime object
Usage
as_difftime(x)Arguments
x | object of class |
Examples
t1 = Sys.time()t2 = t1 + 3600d = t2 - t1du <- as_units(d)dt = as_difftime(du)class(dt)dtboxplot for unit objects
Description
boxplot for unit objects
Usage
## S3 method for class 'units'boxplot(x, ..., horizontal = FALSE)Arguments
x | object of class units, for which we want to plot the boxplot |
... | parameters passed on toboxplot.default |
horizontal | logical indicating if the boxplots should be horizontal;default FALSE means vertical boxes. |
Examples
units_options(parse = FALSE) # otherwise we break on the funny symbol!u = set_units(rnorm(100), degree_C)boxplot(u)Combine R Objects by Rows or Columns
Description
S3 methods forunits objects (seecbind).
Usage
## S3 method for class 'units'cbind(..., deparse.level = 1)## S3 method for class 'units'rbind(..., deparse.level = 1)Arguments
... | (generalized) vectors or matrices. These can be given as namedarguments. OtherR objects may be coerced as appropriate, or S4methods may be used: see sections ‘Details’ and‘Value’. (For the |
deparse.level | integer controlling the construction of labels inthe case of non-matrix-like arguments (for the default method): |
Examples
x <- set_units(1, m/s)y <- set_units(1:3, m/s)z <- set_units(8:10, m/s)(m <- cbind(x, y)) # the '1' (= shorter vector) is recycled(m <- cbind(m, z)[, c(1, 3, 2)]) # insert a column(m <- rbind(m, z)) # insert a rowConvert units to their base units
Description
Convert the units of aunits object to their base units, as defined bythe udunits database (SI units).
Usage
convert_to_base(x, simplify = TRUE, keep_fraction = TRUE)Arguments
x | object of class |
simplify | logical; if TRUE (default), the resulting units are simplified. |
keep_fraction | logical; if TRUE (default), the result is kept as a fraction. |
Value
object of classunits with units converted to base units.
Examples
x <- set_units(32, mJ/g)convert_to_base(x)convert_to_base(x, keep_fraction=FALSE)convert_to_base(x, simplify=FALSE)convert_to_base(x, simplify=FALSE, keep_fraction=FALSE)deparse unit to string in product power form (e.g. km m-2 s-1)
Description
deparse unit to string in product power form (e.g. km m-2 s-1)
Usage
deparse_unit(x)Arguments
x | object of class units |
Value
length one character vector
Examples
u = as_units("kg m-2 s-1")udeparse_unit(u)Drop Units
Description
Drop units attribute and class.
Usage
drop_units(x)## S3 method for class 'units'drop_units(x)## S3 method for class 'data.frame'drop_units(x)## S3 method for class 'mixed_units'drop_units(x)Arguments
x | an object with units metadata. |
Details
Equivalent tounits(x) <- NULL, or the pipe-friendly versionset_units(x, NULL), butdrop_units will fail if the object hasno units metadata. Use the alternatives if you want this operation to succeedregardless of the object type.
Adata.frame method is also provided, which checks every column anddrops units if any.
Value
the numeric without any units attributes, while preserving otherattributes like dimensions or other classes.
Examples
x <- 1y <- set_units(x, m/s)# this succeedsdrop_units(y)set_units(y, NULL)set_units(x, NULL)## Not run: # this failsdrop_units(x)## End(Not run)df <- data.frame(x=x, y=y)dfdrop_units(df)histogram for unit objects
Description
histogram for unit objects
Usage
## S3 method for class 'units'hist(x, xlab = NULL, main = paste("Histogram of", xname), ...)Arguments
x | object of class units, for which we want to plot the histogram |
xlab | character; x axis label |
main | character; title of histogram |
... | parameters passed on tohist.default |
Examples
units_options(parse = FALSE) # otherwise we break on the funny symbol!u = set_units(rnorm(100), degree_C)hist(u)Define or remove units
Description
Installing new symbols and/or names allows them to be used inas_units,make_units andset_units. Optionally, a relationship can bedefined between such symbols/names and existing ones (see details and examples).
Usage
install_unit(symbol = character(0), def = character(0), name = character(0))remove_unit(symbol = character(0), name = character(0))Arguments
symbol | a vector of symbols to be installed/removed. |
def | either
|
name | a vector of names to be installed/removed. |
Details
At least one symbol or name is expected, but multiple symbols and/or namescan be installed (and thus mapped to the same unit) or removed at the sametime. Thedef argument enables arbitrary relationships with existingunits using UDUNITS-2 syntax:
| String Type | Using Names | Using Symbols | Comment |
| Simple | meter | m | |
| Raised | meter^2 | m2 | higher precedence than multiplying or dividing |
| Product | newton meter | N.m | |
| Quotient | meter per second | m/s | |
| Scaled | 60 second | 60 s | |
| Prefixed | kilometer | km | |
| Offset | kelvin from 273.15 | K @ 273.15 | lower precedence than multiplying or dividing |
| Logarithmic | lg(re milliwatt) | lg(re mW) | "lg" is base 10, "ln" is base e, and "lb" is base 2 |
| Grouped | (5 meter)/(30 second) | (5 m)/(30 s) |
The above may be combined, e.g.,"0.1 lg(re m/(5 s)^2) @ 50".You may also look at the<def> elements in the units database to seeexamples of string unit specifications.
Examples
# define a fortnightinstall_unit("fn", "2 week", "fortnight")year <- as_units("year")set_units(year, fn) # by symbolset_units(year, fortnight) # by name# clean upremove_unit("fn", "fortnight")# working with currenciesinstall_unit("dollar")install_unit("euro", "1.22 dollar")install_unit("yen", "0.0079 euro")set_units(as_units("dollar"), yen)# clean upremove_unit(c("dollar", "euro", "yen"))# an example from microbiologycfu_symbols <- c("CFU", "cfu")cfu_names <- c("colony_forming_unit", "ColonyFormingUnit")install_unit("cell")install_unit(cfu_symbols, "3.4 cell", cfu_names)cell <- set_units(2.5e5, cell)vol <- set_units(500, ul)set_units(cell/vol, "cfu/ml")set_units(cell/vol, "CFU/ml")set_units(cell/vol, "colony_forming_unit/ml")set_units(cell/vol, "ColonyFormingUnit/ml")# clean upremove_unit(c("cell", cfu_symbols), cfu_names)Apply a function keeping units
Description
Helper function to apply a function to aunits object and then restorethe original units.
Usage
keep_units(FUN, x, ..., unit = units(x))Arguments
FUN | the function to be applied. |
x | first argument of |
... | optional arguments to |
unit | symbolic unit to restore after |
Details
Provided for incompatible functions that do not preserve units. The user isresponsible for ensuring the correctness of the output.
Ifx is not aunits objectandunit is not provided by the user,a warning is issued, and the output will also have no units(see examples).
Value
An object of classunits.
Examples
x <- set_units(1:5, m)keep_units(drop_units, x)# An example use case is with random number generating functions:mu <- as_units(10, "years")keep_units(rnorm, n = 1, x = mu)# units can be directly specified if needed; for example, with# `rexp()`, the units of the rate parameter are the inverse of# the units of the output:rate <- as_units(3, "1/year")keep_units(rexp, n = 1, x = rate, unit = units(1/rate))# if `x` does not actually have units, a warning is issued,# and the output has no units:rate2 <- 3keep_units(rexp, n = 1, x = rate2)Load a unit system
Description
Load an XML database containing a unit system compatible with UDUNITS2.
Usage
load_units_xml(path = default_units_xml())Arguments
path | a path to a valid unit system in XML format. |
Details
A unit system comprises a root<unit-system> and a number of childrendefining prefixes (<prefix>) or units (<unit>).See the contents of
system.file("share/udunits", package="units")
for examples.
Examples
# load a new unit systemload_units_xml(system.file("share/udunits/udunits2-base.xml", package="units"))## Not run: set_units(1, rad) # doesn'twork## End(Not run)# reload the default unit systemload_units_xml()set_units(1, rad) # works againS3 matrixOps Group Generic Functions for units objects
Description
matrixOps functions for units objects.
Usage
## S3 method for class 'units'matrixOps(x, y)Arguments
x | object of class |
y | object of class |
Value
object of classunits
Examples
a = set_units(1:5, m)a %*% aa %*% t(a)a %*% 1:51:5 %*% aCreate or convert to a mixed units list-column
Description
Create or convert to a mixed units list-column
Usage
mixed_units(x, values, ...)## S3 replacement method for class 'mixed_units'units(x) <- valueArguments
x | numeric, or vector of class |
values | character vector with units encodings, or list with symbolic units of class |
... | ignored |
value | see values |
Details
ifx is of classunits,values should be missing or of classmixed_symbolic_units; ifx is numeric,values should be a character vector the length ofx.
Examples
a <- 1:4u <- c("m/s", "km/h", "mg/L", "g")mixed_units(a, u)units(a) = as_units("m/s")mixed_units(a) # converts to mixed representationPlotunits objects
Description
Create axis label with appropriate labels.
Plot method forunits objects.
Usage
make_unit_label(lab, u, sep = units_options("sep"), group = units_options("group"), parse = units_options("parse"))## S3 method for class 'units'plot(x, y, xlab = NULL, ylab = NULL, ...)Arguments
lab | length one character; name of the variable to plot |
u | vector of class |
sep | length two character vector, defaulting to |
group | length two character vector with grouping symbols, e.g. |
parse | logical; indicates whether a parseable expression should bereturned (typically needed for super scripts), or a simple character stringwithout special formatting. |
x | object of class units, to plot along the x axis, or, if y is missing, along the y axis |
y | object to plot along the y axis, or missing |
xlab | character; x axis label |
ylab | character; y axis label |
... | other parameters, passed on toplot.default |
Details
units_options can be used to set and change the defaults forsep,group anddoParse.
Examples
displacement = mtcars$disp * as_units("in")^3units(displacement) = make_units(cm^3)weight = mtcars$wt * 1000 * make_units(lb)units(weight) = make_units(kg)plot(weight, displacement)units_options(group = c("(", ")") ) # parenthesis instead of square bracketsplot(weight, displacement)units_options(sep = c("~~~", "~"), group = c("", "")) # no brackets; extra spaceplot(weight, displacement)units_options(sep = c("~", "~~"), group = c("[", "]"))gallon = as_units("gallon")consumption = mtcars$mpg * make_units(mi/gallon)units(consumption) = make_units(km/l)plot(displacement, consumption) # division in consumptionunits_options(negative_power = TRUE) # division becomes ^-1plot(displacement, consumption)plot(1/displacement, 1/consumption)Continuous scales for units data
Description
These are the default scales for theunits class. These will usuallybe added automatically. To override manually, usescale_{type}_units.
Usage
scale_x_units(..., sec.axis = ggplot2::waiver(), unit = NULL)scale_y_units(..., sec.axis = ggplot2::waiver(), unit = NULL)scale_colour_units(..., unit = NULL)scale_color_units(..., unit = NULL)scale_fill_units(..., unit = NULL)scale_alpha_units(..., unit = NULL)scale_size_units(..., unit = NULL)scale_size_area_units(..., unit = NULL)scale_radius_units(..., unit = NULL)scale_linewidth_units(..., unit = NULL)Arguments
... | arguments passed on to the corresponding continuous scale(see the manual page for each |
sec.axis |
|
unit | A unit specification to use for the guide. If given, the valueswill be converted to this unit before plotting. An error will be thrown ifthe specified unit is incompatible with the unit of the data. |
Examples
if (requireNamespace("ggplot2", quietly=TRUE)) {library(ggplot2)mtcars$consumption <- set_units(mtcars$mpg, mi / gallon)mtcars$power <- set_units(mtcars$hp, hp)# Use units encoded into the dataggplot(mtcars) + geom_point(aes(power, consumption))# Convert units on the fly during plottingggplot(mtcars) + geom_point(aes(power, consumption)) + scale_x_units(unit = "W") + scale_y_units(unit = "km/l")# Resolve units when transforming dataggplot(mtcars) + geom_point(aes(power, 1 / consumption))# Reverse the y axisggplot(mtcars) + geom_point(aes(power, consumption)) + scale_y_units(transform="reverse")}seq method for units objects
Description
seq method for units objects
Usage
## S3 method for class 'units'seq(from, to, by = ((to - from)/(length.out - 1)), length.out = NULL, along.with = NULL, ...)Arguments
from | seeseq |
to | seeseq |
by | seeseq |
length.out | seeseq |
along.with | seeseq |
... | seeseq |
Details
arguments with units are converted to have units of the first argument (which is eitherfrom orto)
Examples
seq(to = set_units(10, m), by = set_units(1, m), length.out = 5)seq(set_units(10, m), by = set_units(1, m), length.out = 5)seq(set_units(10, m), set_units(19, m))seq(set_units(10, m), set_units(.1, km), set_units(10000, mm))udunits2 utilities
Description
Someudunits2 utilities are exposed to the user. These functions areuseful for checking whether units are convertible or converting between unitswithout having to createunits objects.Arguments are recycled if necessary.
Usage
ud_are_convertible(from, to, ...)ud_convert(x, from, to)Arguments
from,to | character vector or object of class |
... | unused. |
x | numeric vector |
Value
ud_are_convertiblereturnsTRUE if both units exist and are convertible,FALSE otherwise.
ud_convertreturns a numeric vector withx converted to new unit.
Examples
ud_are_convertible(c("m", "mm"), "km")ud_convert(c(100, 100000), c("m", "mm"), "km")a <- set_units(1:3, m/s)ud_are_convertible(units(a), "km/h")ud_convert(1:3, units(a), "km/h")ud_are_convertible("degF", "degC")ud_convert(32, "degF", "degC")The "unit" type for vectors that are actually dimension-less.
Description
The "unit" type for vectors that are actually dimension-less.
Usage
unitlessFormat
An object of classsymbolic_units of length 2.
Handle measurement units
Description
A number of functions are provided for handling unit objects.
`units<-`andunitsare the basic functions to setand retrieve units.as_units, a generic with methods for acharacter string and for quoted language. Note, direct usage of this functionby users is typically not necessary, as coercion viaas_unitsisautomatically done with`units<-`andset_units.make_units, constructs units from bare expressions.make_units(m/s)is equivalent toas_units(quote(m/s)).set_units, a pipe-friendly version of`units<-`. Bydefault it operates with bare expressions, but thisbehavior can be disabled by a specifyingmode = "standard"or settingunits_options(set_units_mode = "standard").Ifvalueis missing or set to1, the object becomes unitless.
Usage
## S3 replacement method for class 'numeric'units(x) <- value## S3 replacement method for class 'units'units(x) <- value## S3 replacement method for class 'logical'units(x) <- value## S3 method for class 'units'units(x)## S3 method for class 'symbolic_units'units(x)set_units(x, value, ..., mode = units_options("set_units_mode"))make_units(bare_expression, check_is_valid = TRUE)as_units(x, ...)## Default S3 method:as_units(x, value = unitless, ...)## S3 method for class 'units'as_units(x, value, ...)## S3 method for class 'symbolic_units'as_units(x, value, ...)## S3 method for class 'difftime'as_units(x, value, ...)## S3 method for class 'character'as_units(x, ..., check_is_valid = TRUE, force_single_symbol = FALSE)## S3 method for class 'call'as_units(x, ...)## S3 method for class 'expression'as_units(x, ...)## S3 method for class 'name'as_units(x, ...)## S3 method for class 'POSIXt'as_units(x, value, ...)## S3 method for class 'Date'as_units(x, value, ...)Arguments
x | numeric vector, or object of class |
value | object of class |
... | passed on to other methods. |
mode | if |
bare_expression | a bare R expression describing units. Must be valid Rsyntax (reserved R syntax words like |
check_is_valid | throw an error if all the unit symbols are not eitherrecognized by udunits2, or a customuser defined via |
force_single_symbol | Whether to perform no string parsing and forcetreatment of the string as a single symbol. |
Details
Ifvalue is of classunits and has a value unequal to 1, thisvalue is ignored unlessunits_options("simplifiy") isTRUE. Ifsimplify isTRUE,x is multiplied by this value.
Value
An object of classunits.
Theunits method retrieves the units attribute, which is ofclasssymbolic_units.
Character strings
Generally speaking, there are 3 types of unit strings are accepted inas_units (and by extension,`units<-`).
The first type, and likely most common, is a "standard" format unitspecification where the relationship between unit symbols or names isspecified explicitly with arithmetic symbols for division/,multiplication* and power exponents^.
The second type of unit string accepted is one with implicit exponents. Inthis format,/,*, and^, may not be present in thestring, and unit symbol or names must be separated by a space. Each unitsymbol may optionally be followed by a single number, specifying the power.For example"m2 s-2" is equivalent to"(m^2)*(s^-2)".
If the string supplied fails to parse, then the string is treated as asingle symbolic unit andsymbolic_unit(chr) is used as a fallbackwith a warning. In that case, automatic unit simplification may not workproperly when performing operations on unit objects, but unit conversionand other Math operations should still give correct results so long asthe unit string supplied returnsTRUE forud_is_parsable().
It must be noted that prepended numbers are supported too, but are nottreated as magnitudes. For example,"1000 m" is interpreted asa prefixed unit, and it is equivalent to"km" to all effects.
The third type of unit string format accepted is the special case ofudunits time duration with a reference origin, for example"hours since 1970-01-01 00:00:00". Note, that the handling of time and calendaroperations via the udunits library is subtly different from the way Rhandles date and time operations. This functionality is mostly exported forusers that work with udunits time data, e.g., with NetCDF files. Users areotherwise encouraged to useR's date and time functionality providedbyDate andPOSIXt classes.
Note
By default, unit names are automatically substituted with unit names(e.g., kilogram –> kg). To turn off this behavior, setunits_options(auto_convert_names_to_symbols = FALSE)
See Also
Examples
x = 1:3class(x)units(x) <- as_units("m/s")class(x)y = 2:5a <- set_units(1:3, m/s)units(a) <- make_units(km/h)a# convert to a mixed_units object:units(a) <- c("m/s", "km/h", "km/h")a# The easiest way to assign units to a numeric vector is like this:x <- y <- 1:4units(x) <- "m/s" # meters / second# Alternatively, the easiest pipe-friendly way to set units:if(requireNamespace("magrittr", quietly = TRUE)) { library(magrittr) y %>% set_units(m/s)}# these are different ways of creating the same unit:# meters per second squared, i.e, accelerationx1 <- make_units(m/s^2)x2 <- as_units(quote(m/s^2))x2 <- as_units("m/s^2")x3 <- as_units("m s-2") # in product power form, i.e., implicit exponents = Tx4 <- set_units(1, m/s^2) # by default, mode = "symbols"x5 <- set_units(1, "m/s^2", mode = "standard")x6 <- set_units(1, x1, mode = "standard")x7 <- set_units(1, units(x1), mode = "standard")x8 <- as_units("m") / as_units("s")^2all_identical <- function(...) { l <- list(...) for(i in seq_along(l)[-1]) if(!identical(l[[1]], l[[i]])) return(FALSE) TRUE}all_identical(x1, x2, x3, x4, x5, x6, x7, x8)# Note, direct usage of these unit creation functions is typically not# necessary, since coercion is automatically done via as_units(). Again,# these are all equivalent ways to generate the same result.x1 <- x2 <- x3 <- x4 <- x5 <- x6 <- x7 <- x8 <- 1:4units(x1) <- "m/s^2"units(x2) <- "m s-2"units(x3) <- quote(m/s^2)units(x4) <- make_units(m/s^2)units(x5) <- as_units(quote(m/s^2))x6 <- set_units(x6, m/s^2)x7 <- set_units(x7, "m/s^2", mode = "standard")x8 <- set_units(x8, units(x1), mode = "standard")all_identical(x1, x2, x3, x4, x5, x6, x7, x8)# Both unit names or symbols can be used. By default, unit names are# automatically converted to unit symbols.make_units(degree_C)make_units(kilogram)make_units(ohm)## Arithmetic operations and units# conversion between unit objects that were defined as symbols and names will# work correctly, although unit simplification in printing may not always occur.x <- 500 * make_units(micrograms/liter)y <- set_units(200, ug/l)x + yx * y # numeric result is correct, but units not simplified completely# note, plural form of unit name accepted too ('liters' vs 'liter'), and# denominator simplification can be performed correctlyx * set_units(5, liters)# unit conversion works tooset_units(x, grams/gallon)## Creating custom, user defined units# For example, a microbiologist might work with counts of bacterial cells# make_units(cells/ml) # by default, throws an ERROR# First define the unit, then the newly defined unit is accepted.install_unit("cells")make_units(cells/ml)# Note that install_unit() adds support for defining relationships between# the newly created symbols or names and existing units.## set_units()# set_units is a pipe friendly version of `units<-`.if(requireNamespace("magrittr", quietly = TRUE)) { library(magrittr) 1:5 %>% set_units(N/m^2) # first sets to m, then converts to km 1:5 %>% set_units(m) %>% set_units(km)}# set_units has two modes of operation. By default, it operates with# bare symbols to define the units.set_units(1:5, m/s)# use `mode = "standard"` to use the value of supplied argument, rather than# the bare symbols of the expression. In this mode, set_units() can be# thought of as a simple alias for `units<-` that is pipe friendly.set_units(1:5, "m/s", mode = "standard")set_units(1:5, make_units(m/s), mode = "standard")# the mode of set_units() can be controlled via a global option# units_options(set_units_mode = "standard")# To remove units useunits(x) <- NULL# orset_units(x, NULL)# ordrop_units(y)s = Sys.time()d = s - (s+1)as_units(d)Defunct functions inunits
Description
These functions are no longer available.
Details
ud_units: Useas_unitsinstead.as.units: Useas_unitsinstead.make_unit: Useas_unitsinstead.parse_unit: Useas_unitsinstead.as_cf: Usedeparse_unitinstead.install_symbolic_unit: Useinstall_unitinstead.remove_symbolic_unit: Useremove_unitinstead.install_conversion_constant: Useinstall_unitinstead.install_conversion_offset: Useinstall_unitinstead.
set one or more units global options
Description
set units global options, mostly related how units are printed and plotted
Usage
units_options(..., sep, group, negative_power, parse, set_units_mode, strict_tokenizer, auto_convert_names_to_symbols, simplify, allow_mixed, unitless_symbol, define_bel)Arguments
... | named options (character) for which the value is queried |
sep | character length two; default |
group | character length two; start and end group, may be two empty strings, a parenthesis pair, or square brackets; default: square brackets. |
negative_power | logical, default |
parse | logical, default |
set_units_mode | character; either |
strict_tokenizer | logical, default |
auto_convert_names_to_symbols | logical, default |
simplify | logical, default |
allow_mixed | logical; if |
unitless_symbol | character; set the symbol to use for unitless (1) units |
define_bel | logical; if |
Details
This sets or gets units options. Set them by using named arguments, get them by passing the option name.
The defaultNA value forsimplify means units are not simplified inset_units oras_units, but are simplified in arithmetical expressions.
Value
in case options are set, invisibly a named list with the option values that are being set; if an option is queried, the current option value.
Examples
old = units_options(sep = c("~~~", "~"), group = c("", "")) # more space, parenthesisold## set back to defaults:units_options(sep = c("~", "~"), group = c("[", "]"), negative_power = FALSE, parse = TRUE)units_options("group")Get information about valid units
Description
These functions require thexml2 package, and return data frames withcomplete information about pre-defined units from UDUNITS2. Inspect this dataframes to determine what inputs are accepted byas_units (and theother functions it powers:as_units,set_units ,units<-).
Usage
valid_udunits(quiet = FALSE)valid_udunits_prefixes(quiet = FALSE)Arguments
quiet | logical, defaults |
Details
Any entry listed undersymbol ,symbol_aliases ,name_singular ,name_singular_aliases ,name_plural , orname_plural_aliases is valid. Additionally, any entry undersymbol orsymbol_aliases may can also contain a valid prefix,as specified byvalid_udunits_prefixes() .
Note, this is primarily intended for interactive use, the exact format of thereturned data frames may change in the future.
Value
a data frame with columnssymbol ,symbol_aliases ,name_singular ,name_singular_aliases ,name_plural ,orname_plural_aliases ,def ,definition ,comment ,dimensionless andsource_xml
Examples
if (requireNamespace("xml2", quietly = TRUE)) { valid_udunits() valid_udunits_prefixes() if(interactive()) View(valid_udunits())}