Debian Codegraph @

R/helpers.R

raw
1 #' Apply a function keeping units
2 #'
3 #' Helper function to apply a function to a \code{units} object and then restore
4 #' the original units.
5 #'
6 #' Provided for incompatible functions that do not preserve units. The user is
7 #' responsible for ensuring the correctness of the output.
8 #'
9 #' If \code{x} is not a \code{units} object
10 #' and \code{unit} is not provided by the user,
11 #' a warning is issued, and the output will also have no units
12 #' (see examples).
13 #'
14 #' @param FUN the function to be applied.
15 #' @param x first argument of \code{FUN}, of class \code{units}.
16 #' @param ... optional arguments to \code{FUN}.
17 #' @param unit symbolic unit to restore after \code{FUN}.
18 #'
19 #' @return An object of class \code{units}.
20 #'
21 #' @examples
22 #' x <- set_units(1:5, m)
23 #' keep_units(drop_units, x)
24 #'
25 #' # An example use case is with random number generating functions:
26 #' mu <- as_units(10, "years")
27 #' keep_units(rnorm, n = 1, x = mu)
28 #'
29 #' # units can be directly specified if needed; for example, with
30 #' # `rexp()`, the units of the rate parameter are the inverse of
31 #' # the units of the output:
32 #' rate <- as_units(3, "1/year")
33 #' keep_units(rexp, n = 1, x = rate, unit = units(1/rate))
34 #'
35 #' # if `x` does not actually have units, a warning is issued,
36 #' # and the output has no units:
37 #' rate2 <- 3
38 #' keep_units(rexp, n = 1, x = rate2)
39 #'
40 #' @export
41 keep_units <- function(FUN, x, ..., unit=units(x)) {
42 if (inherits(try(unit, silent = TRUE), "symbolic_units")) {
43 set_units(do.call(FUN, list(x, ...)), unit, mode = "standard")
44 } else {
45 warning("wrong `unit` specification.")
46 do.call(FUN, list(x, ...))
47 }
48 }
49
50 dfapply <- function(X, FUN, ...) {
51 attrs <- attributes(X)
52 X <- lapply(X, FUN, ...)
53 attributes(X) <- attrs
54 X
55 }