Debian Codegraph @

R/conversion.R

raw
1 #' Handle measurement units
2 #'
3 #' A number of functions are provided for handling unit objects.
4 #' \itemize{
5 #' \item \code{`units<-`} and \code{units} are the basic functions to set
6 #' and retrieve units.
7 #' \item \code{as_units}, a generic with methods for a
8 #' character string and for quoted language. Note, direct usage of this function
9 #' by users is typically not necessary, as coercion via \code{as_units} is
10 #' automatically done with \code{`units<-`} and \code{set_units}.
11 #' \item \code{make_units}, constructs units from bare expressions.
12 #' \code{make_units(m/s)} is equivalent to \code{as_units(quote(m/s))}.
13 #' \item \code{set_units}, a pipe-friendly version of \code{`units<-`}. By
14 #' default it operates with bare expressions, but this
15 #' behavior can be disabled by a specifying \code{mode = "standard"} or setting
16 #' \code{units_options(set_units_mode = "standard")}.
17 #' If \code{value} is missing or set to \code{1}, the object becomes unitless.
18 #' }
19 #'
20 #' @param x numeric vector, or object of class \code{units}.
21 #' @param value object of class \code{units} or \code{symbolic_units}, or in the
22 #' case of \code{set_units} expression with symbols (see examples).
23 #'
24 #' @return An object of class \code{units}.
25 #'
26 #' @details
27 #' If \code{value} is of class \code{units} and has a value unequal to 1, this
28 #' value is ignored unless \code{units_options("simplifiy")} is \code{TRUE}. If
29 #' \code{simplify} is \code{TRUE}, \code{x} is multiplied by this value.
30 #'
31 #' @export
32 #' @name units
33 #'
34 #' @examples
35 #' x = 1:3
36 #' class(x)
37 #' units(x) <- as_units("m/s")
38 #' class(x)
39 #' y = 2:5
40 `units<-.numeric` <- function(x, value) {
41 if(!length(value))
42 return(x)
43
44 storage.mode(x) <- "double" # issues/324
45
46 if(!inherits(value, "units") && !inherits(value, "symbolic_units"))
47 value <- as_units(value)
48
49 if (inherits(value, "units")) {
50 if (any(is.na(value)))
51 stop("a missing value for units is not allowed")
52 if (isTRUE(.units.simplify()))
53 x <- x * unclass(value)
54 else if (any(unclass(value) != 1.0))
55 warning(paste("numeric value", unclass(value), "is ignored in unit assignment"))
56 value <- units(value)
57 }
58
59 attr(x, "units") = value
60 class(x) <- "units"
61 x
62 }
63
64 #' @name units
65 #' @export
66 #'
67 #' @examples
68 #' a <- set_units(1:3, m/s)
69 #' units(a) <- make_units(km/h)
70 #' a
71 #' # convert to a mixed_units object:
72 #' units(a) <- c("m/s", "km/h", "km/h")
73 #' a
74 `units<-.units` <- function(x, value) {
75 if(!length(value))
76 return(drop_units(x))
77
78 if(!inherits(value, "units") && !inherits(value, "symbolic_units")) {
79 if ((is.character(value) && length(value) > 1))
80 return(set_units(mixed_units(x), value))
81 value <- as_units(value)
82 }
83
84 dimx = dim(x)
85 if (inherits(value, "units")) {
86 if (!identical(as.numeric(value), 1))
87 x <- .as.units(unclass(x) * unclass(value), units(x))
88 value <- units(value)
89 }
90
91 if (identical(units(x), value)) # do nothing; possibly user-defined units:
92 return(x)
93
94 str1 <- ud_char(units(x))
95 str2 <- ud_char(value)
96
97 if (ud_are_convertible(str1, str2))
98 .as.units(ud_convert(unclass(x), str1, str2), value, dim = dimx)
99 else
100 stop(paste("cannot convert", units(x), "into", value), call. = FALSE)
101 }
102
103 #unit_ambiguous = function(value) {
104 # msg = paste("ambiguous argument:", value, "is interpreted by its name, not by its value")
105 # warning(msg, call. = FALSE)
106 #}
107
108
109 #' @name units
110 #' @export
111 `units<-.logical` <- function(x, value) {
112 if (!all(is.na(x)))
113 stop("x must be numeric, non-NA logical not supported")
114
115 # x <- as.numeric(x) ## see https://github.com/r-quantities/units/issues/413
116 storage.mode(x) = "numeric"
117 units(x) <- value
118 x
119 }
120
121 #' @return The \code{units} method retrieves the units attribute, which is of
122 #' class \code{symbolic_units}.
123 #'
124 #' @name units
125 #' @export
126 units.units <- function(x) {
127 attr(x, "units")
128 }
129
130 #' @name units
131 #' @export
132 units.symbolic_units <- function(x) {
133 x
134 }
135
136 #' @export
137 as.data.frame.units <- function(x, row.names = NULL, optional = FALSE, ...) {
138 df = as.data.frame(unclass(x), row.names, optional, ...)
139 if (!optional && ncol(df) == 1)
140 colnames(df) <- deparse(substitute(x))
141 dfapply(df, as_units, units(x))
142 }
143
144 #' @export
145 as.list.units <- function(x, ...)
146 lapply(NextMethod(), set_units, units(x), mode="standard")
147
148 #' convert units object into difftime object
149 #'
150 #' @param x object of class \code{units}
151 #'
152 #' @export
153 #' @examples
154 #'
155 #' t1 = Sys.time()
156 #' t2 = t1 + 3600
157 #' d = t2 - t1
158 #' du <- as_units(d)
159 #' dt = as_difftime(du)
160 #' class(dt)
161 #' dt
162 as_difftime <- function(x) {
163 stopifnot(inherits(x, "units"))
164 u <- as.character(units(x))
165 if (u == "s")
166 as.difftime(x, units = "secs")
167 else if (u == "min")
168 as.difftime(x, units = "mins")
169 else if (u == "h")
170 as.difftime(x, units = "hours")
171 else if (u == "d")
172 as.difftime(x, units = "days")
173 else
174 stop(paste("cannot convert unit", u, "to difftime object"))
175 }
176
177 # #' Convert units to hms
178 # #'
179 # #' Convert units to hms
180 # #' @param x object of class units
181 # #' @param ... passed on to as.hms.difftime
182 # #' @return object of class hms
183 # #' @examples
184 # #' if (require(hms)) {
185 # #' as.hms(1:10 * make_units(s))
186 # #' as.hms(1:10 * make_units(min))
187 # #' as.hms(1:10 * make_units(h))
188 # #' as.hms(1:10 * make_units(d))
189 # #' }
190 # #' @export
191 # as.hms.units = function(x, ...) {
192 # hms::as.hms(as_difftime(x), ...)
193 # }
194
195
196 #' @export
197 `[.units` <- function(x, i, j, ..., drop = TRUE) {
198 restore_units(NextMethod(), x)
199 }
200
201 #' @export
202 `[[.units` <- function(x, i, j, ...) {
203 restore_units(NextMethod(), x)
204 }
205
206 #' @export
207 as.POSIXct.units = function (x, tz = "UTC", ...) {
208 units(x) = symbolic_unit("seconds since 1970-01-01 00:00:00 +00:00")
209 as.POSIXct.numeric(as.numeric(x), tz = tz, origin = as.POSIXct("1970-01-01 00:00:00", tz = "UTC"))
210 }
211
212 #' @method as.Date units
213 #' @export
214 as.Date.units = function (x, ...) {
215 units(x) = symbolic_unit("days since 1970-01-01")
216 as.Date(as.numeric(x), origin = as.Date("1970-01-01 00:00:00"))
217 }
218
219 #' @param ... passed on to other methods.
220 #' @param mode if \code{"symbols"} (the default), then unit is constructed from
221 #' the expression supplied. Otherwise, if\code{mode = "standard"},
222 #' standard evaluation is used for the supplied value This argument can be set
223 #' via a global option \code{units_options(set_units_mode = "standard")}
224 #'
225 #' @name units
226 #' @export
227 set_units <- function(x, value, ..., mode = units_options("set_units_mode"))
228 UseMethod("set_units")
229
230 #' @export
231 set_units.numeric <- function(x, value, ..., mode = units_options("set_units_mode")) {
232 if (missing(value))
233 value <- unitless
234 else if (mode == "symbols") {
235 value <- substitute(value)
236 if(is.numeric(value) && !identical(value, 1) && !identical(value, 1L))
237 stop("The only valid number defining a unit is '1', signifying a unitless unit")
238 if (is.name(value) || is.call(value))
239 value <- format(value)
240 }
241
242 units(x) <- as_units(value, ...)
243 x
244 }
245
246 #' @export
247 set_units.logical <- set_units.numeric
248
249 #' @export
250 set_units.units <- set_units.numeric
251
252 #' Drop Units
253 #'
254 #' Drop units attribute and class.
255 #'
256 #' @param x an object with units metadata.
257 #'
258 #' @return the numeric without any units attributes, while preserving other
259 #' attributes like dimensions or other classes.
260 #'
261 #' @details Equivalent to \code{units(x) <- NULL}, or the pipe-friendly version
262 #' \code{set_units(x, NULL)}, but \code{drop_units} will fail if the object has
263 #' no units metadata. Use the alternatives if you want this operation to succeed
264 #' regardless of the object type.
265 #'
266 #' A \code{data.frame} method is also provided, which checks every column and
267 #' drops units if any.
268 #'
269 #' @export
270 #' @examples
271 #' x <- 1
272 #' y <- set_units(x, m/s)
273 #'
274 #' # this succeeds
275 #' drop_units(y)
276 #' set_units(y, NULL)
277 #' set_units(x, NULL)
278 #'
279 #' \dontrun{
280 #' # this fails
281 #' drop_units(x)
282 #' }
283 #'
284 #' df <- data.frame(x=x, y=y)
285 #' df
286 #' drop_units(df)
287 #'
288 drop_units <- function(x) UseMethod("drop_units")
289
290 #' @name drop_units
291 #' @export
292 drop_units.units <- function(x) {
293 class(x) <- setdiff(class(x), "units")
294 attr(x, "units") <- NULL
295 x
296 }
297
298 #' @name drop_units
299 #' @export
300 drop_units.data.frame <- function(x) {
301 dfapply(x, function(i) if (inherits(i, "units")) drop_units(i) else i)
302 }