|
| 1 | +# Modified after https://github.com/tidymodels/yardstick/blob/main/R/aaa-new.R |
| 2 | + |
| 3 | +#' Construct a new measure function |
| 4 | +#' @keywords summary_stats |
| 5 | +#' |
| 6 | +#' @description |
| 7 | +#' These functions provide convenient wrappers to create the three types of |
| 8 | +#' measure functions in `tidyhydro`: measures of central tendency, variability |
| 9 | +#' and symmetry. They add a measure-specific class to `fn` and |
| 10 | +#' mimic a behaviour of [metric_set][yardstick::metric_set]. These features |
| 11 | +#' are used by measure_set. |
| 12 | +#' |
| 13 | +#' See [Custom performance |
| 14 | +#' metrics](https://www.tidymodels.org/learn/develop/metrics/) for more |
| 15 | +#' information about creating custom metrics. |
| 16 | +#' |
| 17 | +#' @param fn A function. The measure function to attach a measure-specific class |
| 18 | +#' |
| 19 | +#' @name new-measure |
| 20 | +NULL |
| 21 | + |
| 22 | +#' @rdname new-measure |
| 23 | +#' @export |
| 24 | +new_tendency_measure <- function(fn) { |
| 25 | + new_measure(fn, class = "tendency_measure") |
| 26 | +} |
| 27 | + |
| 28 | +#' @rdname new-measure |
| 29 | +#' @export |
| 30 | +new_var_measure <- function(fn) { |
| 31 | + new_measure(fn, class = "var_measure") |
| 32 | +} |
| 33 | + |
| 34 | +#' @rdname new-measure |
| 35 | +#' @export |
| 36 | +new_sym_measure <- function(fn) { |
| 37 | + new_measure(fn, class = "sym_measure") |
| 38 | +} |
| 39 | + |
| 40 | +new_measure <- function(fn, class = NULL) { |
| 41 | + checkmate::assert_function(fn, args = "data") |
| 42 | + |
| 43 | + class <- c(class, "measure", "function") |
| 44 | + |
| 45 | + structure(fn, class = class) |
| 46 | +} |
| 47 | + |
| 48 | +is_measure <- function(x) { |
| 49 | + inherits(x, "measure") |
| 50 | +} |
| 51 | + |
| 52 | +#' @noRd |
| 53 | +#' @export |
| 54 | +print.measure <- function(x, ...) { |
| 55 | + cat(format(x), sep = "\n") |
| 56 | + invisible(x) |
| 57 | +} |
| 58 | + |
| 59 | +#' @noRd |
| 60 | +#' @export |
| 61 | +format.measure <- function(x, ...) { |
| 62 | + first_class <- class(x)[[1]] |
| 63 | + measure_type <- |
| 64 | + switch( |
| 65 | + first_class, |
| 66 | + "tendency_measure" = "Measure of Central Tendency", |
| 67 | + "var_measure" = "Measure of Variability", |
| 68 | + "sym_measure" = "Measure of Distribution Symmetry", |
| 69 | + "measure" |
| 70 | + ) |
| 71 | + |
| 72 | + cat(paste("A", measure_type)) |
| 73 | +} |
0 commit comments