| 1 |
# helper function: |
| 2 |
.as.units = function(x, value, dim) { |
| 3 |
if (missing(dim)) |
| 4 |
structure(x, units = value, class = "units") |
| 5 |
else |
| 6 |
structure(x, units = value, dim = dim, class = "units") |
| 7 |
} |
| 8 |
|
| 9 |
#' @name units |
| 10 |
#' @export |
| 11 |
#' |
| 12 |
#' @param bare_expression a bare R expression describing units. Must be valid R |
| 13 |
#' syntax (reserved R syntax words like \code{in} must be backticked) |
| 14 |
#' |
| 15 |
#' @examples |
| 16 |
#' # The easiest way to assign units to a numeric vector is like this: |
| 17 |
#' x <- y <- 1:4 |
| 18 |
#' units(x) <- "m/s" # meters / second |
| 19 |
#' |
| 20 |
#' # Alternatively, the easiest pipe-friendly way to set units: |
| 21 |
#' if(requireNamespace("magrittr", quietly = TRUE)) { |
| 22 |
#' library(magrittr) |
| 23 |
#' y %>% set_units(m/s) |
| 24 |
#' } |
| 25 |
#' |
| 26 |
#' # these are different ways of creating the same unit: |
| 27 |
#' # meters per second squared, i.e, acceleration |
| 28 |
#' x1 <- make_units(m/s^2) |
| 29 |
#' x2 <- as_units(quote(m/s^2)) |
| 30 |
#' x2 <- as_units("m/s^2") |
| 31 |
#' x3 <- as_units("m s-2") # in product power form, i.e., implicit exponents = T |
| 32 |
#' x4 <- set_units(1, m/s^2) # by default, mode = "symbols" |
| 33 |
#' x5 <- set_units(1, "m/s^2", mode = "standard") |
| 34 |
#' x6 <- set_units(1, x1, mode = "standard") |
| 35 |
#' x7 <- set_units(1, units(x1), mode = "standard") |
| 36 |
#' x8 <- as_units("m") / as_units("s")^2 |
| 37 |
#' |
| 38 |
#' all_identical <- function(...) { |
| 39 |
#' l <- list(...) |
| 40 |
#' for(i in seq_along(l)[-1]) |
| 41 |
#' if(!identical(l[[1]], l[[i]])) |
| 42 |
#' return(FALSE) |
| 43 |
#' TRUE |
| 44 |
#' } |
| 45 |
#' all_identical(x1, x2, x3, x4, x5, x6, x7, x8) |
| 46 |
#' |
| 47 |
#' # Note, direct usage of these unit creation functions is typically not |
| 48 |
#' # necessary, since coercion is automatically done via as_units(). Again, |
| 49 |
#' # these are all equivalent ways to generate the same result. |
| 50 |
#' |
| 51 |
#' x1 <- x2 <- x3 <- x4 <- x5 <- x6 <- x7 <- x8 <- 1:4 |
| 52 |
#' units(x1) <- "m/s^2" |
| 53 |
#' units(x2) <- "m s-2" |
| 54 |
#' units(x3) <- quote(m/s^2) |
| 55 |
#' units(x4) <- make_units(m/s^2) |
| 56 |
#' units(x5) <- as_units(quote(m/s^2)) |
| 57 |
#' x6 <- set_units(x6, m/s^2) |
| 58 |
#' x7 <- set_units(x7, "m/s^2", mode = "standard") |
| 59 |
#' x8 <- set_units(x8, units(x1), mode = "standard") |
| 60 |
#' |
| 61 |
#' all_identical(x1, x2, x3, x4, x5, x6, x7, x8) |
| 62 |
#' |
| 63 |
#' |
| 64 |
#' # Both unit names or symbols can be used. By default, unit names are |
| 65 |
#' # automatically converted to unit symbols. |
| 66 |
#' make_units(degree_C) |
| 67 |
#' make_units(kilogram) |
| 68 |
#' make_units(ohm) |
| 69 |
#' |
| 70 |
#' ## Arithmetic operations and units |
| 71 |
#' # conversion between unit objects that were defined as symbols and names will |
| 72 |
#' # work correctly, although unit simplification in printing may not always occur. |
| 73 |
#' x <- 500 * make_units(micrograms/liter) |
| 74 |
#' y <- set_units(200, ug/l) |
| 75 |
#' x + y |
| 76 |
#' x * y # numeric result is correct, but units not simplified completely |
| 77 |
#' |
| 78 |
#' # note, plural form of unit name accepted too ('liters' vs 'liter'), and |
| 79 |
#' # denominator simplification can be performed correctly |
| 80 |
#' x * set_units(5, liters) |
| 81 |
#' |
| 82 |
#' # unit conversion works too |
| 83 |
#' set_units(x, grams/gallon) |
| 84 |
#' |
| 85 |
#' ## Creating custom, user defined units |
| 86 |
#' # For example, a microbiologist might work with counts of bacterial cells |
| 87 |
#' # make_units(cells/ml) # by default, throws an ERROR |
| 88 |
#' # First define the unit, then the newly defined unit is accepted. |
| 89 |
#' install_unit("cells") |
| 90 |
#' make_units(cells/ml) |
| 91 |
#' |
| 92 |
#' # Note that install_unit() adds support for defining relationships between |
| 93 |
#' # the newly created symbols or names and existing units. |
| 94 |
#' |
| 95 |
#' ## set_units() |
| 96 |
#' # set_units is a pipe friendly version of `units<-`. |
| 97 |
#' if(requireNamespace("magrittr", quietly = TRUE)) { |
| 98 |
#' library(magrittr) |
| 99 |
#' 1:5 %>% set_units(N/m^2) |
| 100 |
#' # first sets to m, then converts to km |
| 101 |
#' 1:5 %>% set_units(m) %>% set_units(km) |
| 102 |
#' } |
| 103 |
#' |
| 104 |
#' # set_units has two modes of operation. By default, it operates with |
| 105 |
#' # bare symbols to define the units. |
| 106 |
#' set_units(1:5, m/s) |
| 107 |
#' |
| 108 |
#' # use `mode = "standard"` to use the value of supplied argument, rather than |
| 109 |
#' # the bare symbols of the expression. In this mode, set_units() can be |
| 110 |
#' # thought of as a simple alias for `units<-` that is pipe friendly. |
| 111 |
#' set_units(1:5, "m/s", mode = "standard") |
| 112 |
#' set_units(1:5, make_units(m/s), mode = "standard") |
| 113 |
#' |
| 114 |
#' # the mode of set_units() can be controlled via a global option |
| 115 |
#' # units_options(set_units_mode = "standard") |
| 116 |
#' |
| 117 |
#' # To remove units use |
| 118 |
#' units(x) <- NULL |
| 119 |
#' # or |
| 120 |
#' set_units(x, NULL) |
| 121 |
#' # or |
| 122 |
#' drop_units(y) |
| 123 |
make_units <- function(bare_expression, check_is_valid = TRUE) { |
| 124 |
as_units(format(substitute(bare_expression)), check_is_valid = check_is_valid) |
| 125 |
} |
| 126 |
|
| 127 |
#' @name units |
| 128 |
#' @export |
| 129 |
as_units <- function(x, ...) { |
| 130 |
UseMethod("as_units") |
| 131 |
} |
| 132 |
|
| 133 |
#' @name units |
| 134 |
#' @export |
| 135 |
as_units.default <- function(x, value = unitless, ...) { |
| 136 |
if (is.null(x)) return(x) |
| 137 |
units(x) <- value |
| 138 |
x |
| 139 |
} |
| 140 |
|
| 141 |
#' @name units |
| 142 |
#' @export |
| 143 |
as_units.units <- function(x, value, ...) { |
| 144 |
if(!missing(value) && !identical(units(value), units(x))) |
| 145 |
warning("Use set_units() to perform unit conversion. Return unit unmodified") |
| 146 |
x |
| 147 |
} |
| 148 |
|
| 149 |
#' @name units |
| 150 |
#' @export |
| 151 |
as_units.symbolic_units <- function(x, value, ...) { |
| 152 |
if(!missing(value)) |
| 153 |
warning("supplied value ignored") |
| 154 |
.as.units(1L, x) |
| 155 |
} |
| 156 |
|
| 157 |
#' @examples |
| 158 |
#' s = Sys.time() |
| 159 |
#' d = s - (s+1) |
| 160 |
#' as_units(d) |
| 161 |
#' |
| 162 |
#' @name units |
| 163 |
#' @export |
| 164 |
as_units.difftime <- function(x, value, ...) { |
| 165 |
u <- attr(x, "units") |
| 166 |
x <- unclass(x) |
| 167 |
attr(x, "units") <- NULL |
| 168 |
|
| 169 |
# convert from difftime to udunits2: |
| 170 |
if (u == "secs") # secs -> s |
| 171 |
x <- x * symbolic_unit("s") |
| 172 |
else if (u == "mins") # mins -> min |
| 173 |
x <- x * symbolic_unit("min") |
| 174 |
else if (u == "hours") # hours -> h |
| 175 |
x <- x * symbolic_unit("h") |
| 176 |
else if (u == "days") # days -> d |
| 177 |
x <- x * symbolic_unit("d") |
| 178 |
else if (u == "weeks") { # weeks -> 7 days |
| 179 |
x <- 7 * x |
| 180 |
x <- x * symbolic_unit("d") |
| 181 |
} else |
| 182 |
stop(paste("unknown time units", u, "in difftime object")) |
| 183 |
|
| 184 |
if (!missing(value)) # convert optionally: |
| 185 |
units(x) <- value |
| 186 |
|
| 187 |
x |
| 188 |
} |
| 189 |
|
| 190 |
# ----- as_units.character helpers ------ |
| 191 |
|
| 192 |
is_udunits_time <- function(s) { |
| 193 |
ud_is_parseable(s) && ud_are_convertible(s, "seconds since 1970-01-01") |
| 194 |
} |
| 195 |
|
| 196 |
# from package:yasp, paste collapse with serial (oxford) comma |
| 197 |
pc_and <- function(..., sep = "") { |
| 198 |
x <- paste(..., sep = sep, collapse = NULL) |
| 199 |
lx <- length(x) |
| 200 |
if(lx == 0L) |
| 201 |
"" |
| 202 |
else if (lx == 1L) |
| 203 |
x |
| 204 |
else if (lx == 2L) |
| 205 |
paste0(x, collapse = " and ") |
| 206 |
else |
| 207 |
paste0( paste0(x[-lx], collapse = ", "), ", and ", x[lx]) |
| 208 |
} |
| 209 |
|
| 210 |
.msg_units_not_recognized <- function(unrecognized_symbols, full_expr) { |
| 211 |
|
| 212 |
if (is.language(full_expr)) |
| 213 |
full_expr <- deparse(full_expr) |
| 214 |
|
| 215 |
is_are <- if (length(unrecognized_symbols) > 1L) "are" else "is" |
| 216 |
|
| 217 |
paste0("In ", sQuote(full_expr), ", ", |
| 218 |
pc_and(sQuote(unrecognized_symbols)), " ", is_are, " not recognized by udunits.\n\n", |
| 219 |
"See a table of valid unit symbols and names with valid_udunits().\n", |
| 220 |
"Custom user-defined units can be added with install_unit().\n\n", |
| 221 |
"See a table of valid unit prefixes with valid_udunits_prefixes().\n", |
| 222 |
"Prefixes will automatically work with any user-defined unit.") |
| 223 |
} |
| 224 |
|
| 225 |
#' @name units |
| 226 |
#' @export |
| 227 |
#' |
| 228 |
#' @param check_is_valid throw an error if all the unit symbols are not either |
| 229 |
#' recognized by udunits2, or a custom |
| 230 |
#' user defined via \code{install_unit()}. If \code{FALSE}, no check |
| 231 |
#' for validity is performed. |
| 232 |
#' |
| 233 |
#' @param force_single_symbol Whether to perform no string parsing and force |
| 234 |
#' treatment of the string as a single symbol. |
| 235 |
#' |
| 236 |
#' @section Character strings: |
| 237 |
#' |
| 238 |
#' Generally speaking, there are 3 types of unit strings are accepted in |
| 239 |
#' \code{as_units} (and by extension, \code{`units<-`}). |
| 240 |
#' |
| 241 |
#' The first type, and likely most common, is a "standard" format unit |
| 242 |
#' specification where the relationship between unit symbols or names is |
| 243 |
#' specified explicitly with arithmetic symbols for division \code{/}, |
| 244 |
#' multiplication \code{*} and power exponents \code{^}. |
| 245 |
#' |
| 246 |
#' The second type of unit string accepted is one with implicit exponents. In |
| 247 |
#' this format, \code{/}, \code{*}, and \code{^}, may not be present in the |
| 248 |
#' string, and unit symbol or names must be separated by a space. Each unit |
| 249 |
#' symbol may optionally be followed by a single number, specifying the power. |
| 250 |
#' For example \code{"m2 s-2"} is equivalent to \code{"(m^2)*(s^-2)"}. |
| 251 |
#' |
| 252 |
#' If the string supplied fails to parse, then the string is treated as a |
| 253 |
#' single symbolic unit and \code{symbolic_unit(chr)} is used as a fallback |
| 254 |
#' with a warning. In that case, automatic unit simplification may not work |
| 255 |
#' properly when performing operations on unit objects, but unit conversion |
| 256 |
#' and other Math operations should still give correct results so long as |
| 257 |
#' the unit string supplied returns \code{TRUE} for \code{ud_is_parsable()}. |
| 258 |
#' |
| 259 |
#' It must be noted that prepended numbers are supported too, but are not |
| 260 |
#' treated as magnitudes. For example, \code{"1000 m"} is interpreted as |
| 261 |
#' a prefixed unit, and it is equivalent to \code{"km"} to all effects. |
| 262 |
#' |
| 263 |
#' The third type of unit string format accepted is the special case of |
| 264 |
#' udunits time duration with a reference origin, for example \code{"hours |
| 265 |
#' since 1970-01-01 00:00:00"}. Note, that the handling of time and calendar |
| 266 |
#' operations via the udunits library is subtly different from the way R |
| 267 |
#' handles date and time operations. This functionality is mostly exported for |
| 268 |
#' users that work with udunits time data, e.g., with NetCDF files. Users are |
| 269 |
#' otherwise encouraged to use \code{R}'s date and time functionality provided |
| 270 |
#' by \code{Date} and \code{POSIXt} classes. |
| 271 |
#' |
| 272 |
#' @note By default, unit names are automatically substituted with unit names |
| 273 |
#' (e.g., kilogram --> kg). To turn off this behavior, set |
| 274 |
#' \code{units_options(auto_convert_names_to_symbols = FALSE)} |
| 275 |
#' |
| 276 |
#' @seealso \code{\link{install_unit}}, \code{\link{valid_udunits}} |
| 277 |
as_units.character <- function(x, ..., |
| 278 |
check_is_valid = TRUE, |
| 279 |
force_single_symbol = FALSE) { |
| 280 |
|
| 281 |
stopifnot(is.character(x), length(x) == 1) |
| 282 |
|
| 283 |
if (any(is.na(x))) |
| 284 |
stop("a missing value for units is not allowed") |
| 285 |
|
| 286 |
if (isTRUE(x == "" || x == "1")) |
| 287 |
return(.as.units(1, unitless)) |
| 288 |
|
| 289 |
if(force_single_symbol || is_udunits_time(x)) |
| 290 |
return(symbolic_unit(x, check_is_valid = check_is_valid)) |
| 291 |
|
| 292 |
o <- try(su <- parse_unit(x, units_options("strict_tokenizer")), silent=TRUE) |
| 293 |
if(inherits(o, "try-error")) { |
| 294 |
warning("Could not parse expression: ", sQuote(x), # nocov |
| 295 |
". Returning as a single symbolic unit()", call. = FALSE) # nocov |
| 296 |
return(symbolic_unit(x, check_is_valid = check_is_valid)) # nocov |
| 297 |
} |
| 298 |
|
| 299 |
if (check_is_valid) { |
| 300 |
vars <- c(su$numerator, su$denominator) |
| 301 |
valid <- vapply(vars, ud_is_parseable, logical(1L)) |
| 302 |
if (!all(valid)) |
| 303 |
stop(.msg_units_not_recognized(vars[!valid], x), call. = FALSE) |
| 304 |
} |
| 305 |
|
| 306 |
if (units_options("auto_convert_names_to_symbols")) { |
| 307 |
name_to_symbol <- function(chr) |
| 308 |
if (ud_is_parseable(chr) && length(sym <- ud_get_symbol(chr))) sym else chr |
| 309 |
su$numerator <- vapply(su$numerator, name_to_symbol, character(1), USE.NAMES=FALSE) |
| 310 |
su$denominator <- vapply(su$denominator, name_to_symbol, character(1), USE.NAMES=FALSE) |
| 311 |
} |
| 312 |
|
| 313 |
if (is.na(.units.simplify())) { |
| 314 |
units_options(simplify = FALSE) |
| 315 |
on.exit(units_options(simplify = NA)) |
| 316 |
} |
| 317 |
.simplify_units(1, su) |
| 318 |
} |
| 319 |
|
| 320 |
#' @name units |
| 321 |
#' @export |
| 322 |
as_units.call <- function(x, ...) { |
| 323 |
as_units(format(x), ...) |
| 324 |
} |
| 325 |
|
| 326 |
#' @name units |
| 327 |
#' @export |
| 328 |
as_units.expression <- function(x, ...) { |
| 329 |
as_units(as.character(x), ...) |
| 330 |
} |
| 331 |
|
| 332 |
#' @name units |
| 333 |
#' @export |
| 334 |
as_units.name <- as_units.expression |
| 335 |
|
| 336 |
#' @name units |
| 337 |
#' @export |
| 338 |
as_units.POSIXt = function(x, value, ...) { |
| 339 |
u = as.numeric(as.POSIXct(x)) |
| 340 |
units(u) = symbolic_unit("seconds since 1970-01-01 00:00:00 +00:00") |
| 341 |
if (! missing(value)) |
| 342 |
units(u) = symbolic_unit(value) |
| 343 |
u |
| 344 |
} |
| 345 |
|
| 346 |
#' @name units |
| 347 |
#' @export |
| 348 |
as_units.Date = function(x, value, ...) { |
| 349 |
u = as.numeric(x) |
| 350 |
units(u) = symbolic_unit("days since 1970-01-01") |
| 351 |
if (!missing(value)) |
| 352 |
units(u) = symbolic_unit(value) |
| 353 |
u |
| 354 |
} |
| 355 |
|
| 356 |
|
| 357 |
symbolic_unit <- function(chr, check_is_valid = TRUE) { |
| 358 |
stopifnot(is.character(chr), length(chr) == 1) |
| 359 |
|
| 360 |
if (check_is_valid && !ud_is_parseable(chr)) { |
| 361 |
msg <- paste(sQuote(chr), "is not a unit recognized by udunits or a user-defined unit") |
| 362 |
stop(msg, call. = FALSE) |
| 363 |
} |
| 364 |
|
| 365 |
auto_convert <- units_options("auto_convert_names_to_symbols") |
| 366 |
if (auto_convert && ud_is_parseable(chr)) { |
| 367 |
sym <- ud_get_symbol(chr) |
| 368 |
if (length(sym)) |
| 369 |
chr <- sym |
| 370 |
} |
| 371 |
|
| 372 |
.as.units(1, .symbolic_units(chr)) |
| 373 |
} |