| 1 |
# Inside the group generic functions we do have .Generic even if the diagnostics |
| 2 |
# think we do not. |
| 3 |
# !diagnostics suppress=.Generic |
| 4 |
|
| 5 |
#' @export |
| 6 |
Summary.units = function(..., na.rm = FALSE) { |
| 7 |
OK <- switch(.Generic, "sum" = , "min" = , "max" = , "range" = TRUE, FALSE) |
| 8 |
if (! OK) |
| 9 |
stop(paste("Summary operation", .Generic, "not allowed")) |
| 10 |
|
| 11 |
args <- list(...) |
| 12 |
if (length(args) > 1) { |
| 13 |
args <- do.call(c, args) # turns args into a single units vector |
| 14 |
do.call(.Generic, c(list(args), na.rm = na.rm)) # concatenate, convert if necessary, re-call with length 1 arg |
| 15 |
} else |
| 16 |
.as.units(NextMethod(), units(args[[1]])) |
| 17 |
} |
| 18 |
|
| 19 |
|
| 20 |
#' @export |
| 21 |
print.units = function (x, ...) { |
| 22 |
gr = units_options("group") |
| 23 |
if (is.array(x) || length(x) > 1L) { |
| 24 |
cat("Units: ", paste0(gr[1], as.character(attr(x, "units")), gr[2]), "\n", sep = "") |
| 25 |
x_next <- drop_units(x) |
| 26 |
attr(x_next, "pillar") <- NULL |
| 27 |
print(x_next, ...) |
| 28 |
} else { |
| 29 |
cat(format(x, ...), "\n", sep="") |
| 30 |
} |
| 31 |
invisible(x) |
| 32 |
} |
| 33 |
|
| 34 |
#' @export |
| 35 |
mean.units = function(x, ...) { |
| 36 |
.as.units(NextMethod(), units(x)) |
| 37 |
} |
| 38 |
|
| 39 |
#' @export |
| 40 |
weighted.mean.units = function(x, w, ...) { |
| 41 |
u <- units(x) |
| 42 |
x <- drop_units(x) |
| 43 |
if (!missing(w)) |
| 44 |
w <- unclass(w) |
| 45 |
.as.units(NextMethod(), u) |
| 46 |
} |
| 47 |
|
| 48 |
#' @export |
| 49 |
median.units = mean.units |
| 50 |
|
| 51 |
#' @export |
| 52 |
quantile.units = function(x, ...) { |
| 53 |
.as.units(quantile(unclass(x), ...), units(x)) |
| 54 |
} |
| 55 |
|
| 56 |
#' @export |
| 57 |
format.units = function(x, ...) { |
| 58 |
gr = units_options("group") |
| 59 |
u = paste0(gr[1], units(x), gr[2]) |
| 60 |
x <- drop_units(x) |
| 61 |
setNames(paste(NextMethod(), u), names(x)) |
| 62 |
} |
| 63 |
|
| 64 |
#' @export |
| 65 |
summary.units = function(object, ...) { |
| 66 |
summary(unclass(object), ...) |
| 67 |
} |