R/udunits.R

Defines functions ud_is_parseable ud_get_symbol ud_are_convertible

Documented in ud_are_convertible

#' Test if two units are convertible
#'
#' Parses and checks whether units can be converted by UDUNITS-2. Units may not
#' be convertible either because they are different magnitudes or because one
#' (or both) units are not defined in the database.
#'
#' @param x character or object of class \code{symbolic_units}, for the symbol
#' of the first unit.
#' @param y character or object of class \code{symbolic_units}, for the symbol
#' of the second unit.
#'
#' @return boolean, \code{TRUE} if both units exist and are convertible.
#' @export
#'
#' @examples
#' ud_are_convertible("m", "km")
#' a <- set_units(1:3, m/s)
#' ud_are_convertible(units(a), "km/h")
#' ud_are_convertible("s", "kg")
ud_are_convertible = function(x, y) {
	stopifnot(inherits(x, c("character", "symbolic_units")), inherits(y, c("character", "symbolic_units")))
	res <- try(R_ut_are_convertible(
	  R_ut_parse(as.character(x)), R_ut_parse(as.character(y))), silent = TRUE)
	! inherits(res, "try-error") && res
}

ud_get_symbol = function(u) {
  u <- R_ut_parse(u)
	sym = R_ut_get_symbol(u)
	if (!length(sym))
		sym = R_ut_get_name(u)
	sym
}

ud_is_parseable = function(u) {
	res <- try(R_ut_parse(u), silent = TRUE)
	! inherits(res, "try-error")
}
edzer/units documentation built on March 27, 2024, 1:19 p.m.