Nothing
#' @include function-factory-helpers.R seq-predicates.R
# This factory needs a linear sequence with dispersion, which neither
# `disperse()` (pair-based, as in `function_map_total_n()`) nor `base::seq()`
# builds. `seq_disperse_df()` does; `function_map_seq_proto()` uses
# `seq_disperse_df_internal()`, a lightweight version of it.
function_map_seq_proto <- function(
fn,
dispersion,
include_reported,
name_key_result = "consistency"
) {
# --- Start of the manufactured helper function ---
function(data, .var, .out_min, .out_max, .cases, ...) {
# A case can be decided with a value missing, if the other values rule it
# out, as in `grimmer(x = 5.19, sd = NA, n = 28)`. There is nothing to
# disperse that value from, but the others still are:
has_var <- !is.na(data[[.var]])
if (!any(has_var)) {
return(NULL)
}
data <- data[has_var, ]
.cases <- .cases[has_var]
# A `digits_*` argument is a single value or one per row of `data`:
dots <- list(...)
names_digits <- grep("^digits_", names(dots), value = TRUE)
for (name in names_digits) {
if (length(dots[[name]]) > 1L) {
dots[[name]] <- dots[[name]][has_var]
}
}
# The step size comes from the caller's `digits_*` argument, not from the
# values: a mean reported as 5.30 is stored as `5.3`, so `seq_disperse()`
# would step by 0.1 instead of 0.01, and only in the rows that lost a
# trailing zero. There is no `digits_n`, so `n` steps by whole numbers.
digits_var <- dots[[paste0("digits_", .var)]]
by_var <- if (is.null(digits_var)) list(NULL) else 1 / (10^digits_var)
# One data frame with a dispersed `.var` sequence per value set:
df_var <- Map(
function(from, by) {
seq_disperse_df_internal(
from,
by = by,
dispersion = dispersion,
offset_from = 0,
out_min = .out_min,
out_max = .out_max,
include_reported = include_reported,
track_diff_var = TRUE
)
},
data[[.var]],
by_var
)
nrow_list_var <- vapply(df_var, nrow, integer(1L), USE.NAMES = FALSE)
df_var <- df_var |>
purrr::list_rbind()
# Everything to the left of the key result column is input to the test:
cols_for_testing_names <-
colnames(data)[seq_len(match(name_key_result, colnames(data)) - 1L)]
cols_for_testing_names_without_var <-
cols_for_testing_names[cols_for_testing_names != .var]
# Repeat the other columns to the length of the sequences, insert the
# dispersed `.var` at its original position, test, and add `diff_var`, the
# distance from the reported value, and `case`, the row number in the
# mapper's input. Row indexing also works when `.var` is the only key
# column, where there is nothing to repeat but the row count.
data_seq <- data[cols_for_testing_names_without_var]
data_seq <- data_seq[rep(seq_len(nrow(data_seq)), nrow_list_var), ] |>
dplyr::mutate(
{{ .var }} := df_var[[1L]],
.before = all_of(match(.var, colnames(data)))
)
cases_seq <- rep(as.integer(.cases), nrow_list_var)
# One `digits_*` value per dispersed row, from that of its case:
for (name in names_digits) {
if (length(dots[[name]]) > 1L) {
dots[[name]] <- rep(dots[[name]], nrow_list_var)
}
}
# A row of `data_seq` is a dispersed value set, not a row of the user's
# `data`:
do.call(fn, c(list(data_seq), dots)) |>
with_rows_of_data(cases_seq) |>
dplyr::mutate(
diff_var = as_integer_if_lossless(df_var$diff_var),
case = cases_seq
)
}
# --- End of the manufactured helper function ---
}
#' Create new `*_map_seq()` functions
#'
#' @description `function_map_seq()` creates a sequence mapper from a basic
#' mapper such as [`grim_map()`]: a function that varies the reported values
#' a few steps up and down and tests each resulting value set, as
#' [`grim_map_seq()`] does. By default, only inconsistent value sets are
#' dispersed.
#'
#' See `vignette("consistency-tests-in-depth")`, section *Sequence mapper*.
#'
#' `function_map_seq()` is a developer tool: it may change in a minor
#' release, with a NEWS entry.
#'
#' @param .fn A basic mapper function such as [`grim_map()`], typically made
#' by [`function_map()`]. It must return its input data frame with a logical
#' column named by `.name_key_result` added.
#' @param .var String. The variables that the factory-made function disperses
#' by default. Defaults to `.reported`.
#' @param .reported String. All variables the factory-made function can
#' disperse.
#' @param .name_test String (length 1). Plain-text name of the test, such as
#' `"GRIM"`, for messages and the output's class.
#' @param .name_key_result (Experimental) String (length 1). Name of the key
#' result column. Default is `"consistency"`. Must be the value that `.fn`
#' was created with.
#' @param .name_class String. Optionally, one or more classes to add to the
#' output. Default is `NULL`.
#' @param .args_disabled String. Optionally, names of arguments of `.fn` that
#' the factory-made function should reject.
#' @param .dispersion Numeric. Steps up and down from the reported values, in
#' units of the last decimal place. Default is `1:5`.
#' @param .out_min,.out_max Limits on the dispersed values. A number applies to
#' every dispersed variable, and `NULL` removes the limit. Default is
#' `"auto"`, which takes the limit from `.var_bounds`.
#' @param .var_bounds Named list, or `NULL` (the default). Each element is named
#' after a variable in `.reported` and is a numeric vector of its least and
#' greatest possible value, with `NA` for an unbounded side, such as `list(n =
#' c(1, NA), sd = c(0, NA))`. A variable not named here is unbounded, except
#' for `n`, which always has a minimum of 1. For a bound that depends on a
#' setting, an element may also be a function that takes the settings `.fn`
#' recorded for its call, as a named list such as `list(sd_meaning =
#' "sd_sample")`, and returns such a vector. The bounds only keep impossible
#' values, such as a sample size of 0, from being tested. They have no
#' bearing on consistency.
#' @param .include_reported Logical. Should the reported values themselves be
#' part of the sequences? Default is `FALSE`.
#' @param .include_consistent Logical. Should consistent value sets be
#' dispersed as well? Default is `FALSE`.
#' @param ... These dots must be empty.
#'
#' @details The arguments of `function_map_seq()` set the defaults of the
#' corresponding arguments of the factory-made function, which can be
#' overridden in each call.
#'
#' Each variable in `var` is dispersed around its own reported value while
#' the others stay as reported.
#'
#' To export a factory-made function from another package, follow the
#' [purrr FAQ on adverbs](https://purrr.tidyverse.org/reference/faq-adverbs-export.html);
#' see `vignette("consistency-tests-in-depth")`, section *Context and
#' export*.
#'
#' @return A function such as these:
#'
#' | \strong{Factory-made function} | \strong{Dispersed variables} | \strong{Test vignette}
#' | --- | --- | ---
#' | [`grim_map_seq()`] | `"x"`, `"n"` | `vignette("grim-in-depth")`
#' | [`grimmer_map_seq()`] | `"x"`, `"sd"`, `"n"` | `vignette("grimmer-in-depth")`
#' | [`debit_map_seq()`] | `"x"`, `"sd"`, `"n"` | `vignette("debit")`
#'
#' The settings of `.fn`, i.e., its arguments after `...`, such as
#' `rounding`, are arguments of this function as well, with the same
#' defaults. So are its helper arguments, such as `items_averaged`. Its `...`
#' pass any other arguments on to `.fn`, which is only of use for a `.fn`
#' without `...` of its own.
#'
#' @include function-factory-helpers.R
#'
#' @export
#'
#' @section Conventions: Name the factory-made function after `.fn` with
#' `_seq` appended, as in [`grim_map_seq()`] from [`grim_map()`]. The output
#' has the classes `"scrutiny_map_seq"` and
#' `"scrutiny_{tolower(.name_test)}_map_seq"`. Prefix any class you add via
#' `.name_class` with your package's name, as in `"mypkg_schlim_map_seq"`.
#'
#' @examples
#' # Function definition of `grim_map_seq()`:
#' grim_map_seq <- function_map_seq(
#' .fn = grim_map,
#' .reported = c("x", "n"),
#' .name_test = "GRIM"
#' )
function_map_seq <- function(
.fn,
.var = .reported,
.reported,
.name_test,
.name_key_result = "consistency",
.name_class = NULL,
.args_disabled = NULL,
.dispersion = 1:5,
.out_min = "auto",
.out_max = "auto",
.var_bounds = NULL,
.include_reported = FALSE,
.include_consistent = FALSE,
...
) {
force(.fn)
force(.var)
force(.reported)
# Its own arguments, the variables its body assigns before reading the key
# arguments, and the columns it adds:
check_reported_reserved(
.reported,
c(
"data",
"var",
"dispersion",
"out_min",
"out_max",
"include_reported",
"include_consistent",
"diff_var",
"case",
"fn",
"reported",
"name_test",
"name_fn",
"name_class",
"name_key_result",
"args_disabled",
"helper_vals",
"setting_vals",
"arg_helper",
"arg_setting"
),
"function_map_seq"
)
force(.name_test)
force(.name_key_result)
check_string(.name_key_result)
check_fn_wrappable(
.fn,
.name_key_result,
c("var", "case", "diff_var"),
"function_map_seq"
)
force(.name_class)
# A class added here comes first; see `R/bind-rows.R`:
register_bind_methods(.name_class[1L])
force(.args_disabled)
force(.dispersion)
force(.out_min)
force(.out_max)
force(.var_bounds)
force(.include_reported)
force(.include_consistent)
# The dots only prevent a false-positive CRAN warning:
rlang::check_dots_empty()
check_args_disabled_unnamed(.args_disabled)
check_var_bounds(.var_bounds)
name_fn <- deparse(substitute(.fn))
# Helper arguments of `.fn`, such as `items_averaged`. The re-tests below
# read them from columns, so they must not also get them as arguments. A
# mapper not made by `function_map()` has no such attribute:
args_helper_fn <- attr(.fn, "scrutiny_args_helper", exact = TRUE)
# They are arguments of the sequence mapper as well, with `.fn`'s defaults,
# i.e., none for `items_averaged`:
helper_formals <- formals(.fn)[args_helper_fn]
# The settings of `.fn`, such as `rounding`, are arguments of the sequence
# mapper as well, again with `.fn`'s defaults. A disabled one stays in the
# dots, where `check_args_disabled()` catches it:
setting_formals <- formals_settings(
.fn,
exclude = c(
args_helper_fn,
.args_disabled,
"var",
"dispersion",
"out_min",
"out_max",
"include_reported",
"include_consistent"
)
)
args_setting_fn <- names(setting_formals)
# `n` holds whole numbers, which print better as integer:
code_bind_cols <- if (any(.reported == "n")) {
rlang::expr({
out <- out |>
purrr::list_rbind() |>
dplyr::mutate(var, n = as_integer_if_lossless(n))
})
} else {
rlang::expr({
out <- out |>
purrr::list_rbind() |>
dplyr::mutate(var)
})
}
# `digits_x` for `grim_map()`, `digits_x` and `digits_sd` for
# `grimmer_map()`:
digits_args_names <- intersect(
paste0("digits_", .reported[.reported != "n"]),
names(formals(.fn))
)
# With `.fn`'s defaults, i.e., none: a default of `NULL` would show in the
# usage as if the arguments could be left out.
digits_pairlist_entries <- formals(.fn)[digits_args_names]
# Other arguments that the basic mapper takes one value per row of:
args_by_row_fn <- setdiff(
attr(.fn, "scrutiny_args_by_row", exact = TRUE),
digits_args_names
)
# The sequence mapper's own settings are recorded next to those of `.fn`,
# and compared to these defaults:
defaults_seq <- list(
var = .var,
dispersion = .dispersion,
out_min = .out_min,
out_max = .out_max,
include_reported = .include_reported,
include_consistent = .include_consistent
)
# --- Start of the manufactured function, `fn_out()` ---
fn_out <- rlang::new_function(
args = rlang::pairlist2(
data = ,
!!!digits_pairlist_entries,
# After the key arguments, as in `function_map()`:
... = ,
!!!helper_formals,
!!!setting_formals,
var = .var,
dispersion = .dispersion,
out_min = .out_min,
out_max = .out_max,
include_reported = .include_reported,
include_consistent = .include_consistent
),
body = rlang::expr({
# Collect the helper arguments that were given, first thing, before any
# local variable could shadow one. A missing one is left out, so that it
# reaches `fn()` as missing, which then says how to supply it:
helper_vals <- list()
for (arg_helper in `!!`(args_helper_fn)) {
if (!eval(call("missing", as.name(arg_helper)))) {
helper_vals[arg_helper] <- list(get(arg_helper))
}
}
# The same for the settings. One that was not given is left out, so that
# `fn()` applies its own default, which is the same:
setting_vals <- list()
for (arg_setting in `!!`(args_setting_fn)) {
if (!eval(call("missing", as.name(arg_setting)))) {
setting_vals[arg_setting] <- list(get(arg_setting))
}
}
name_test <- `!!`(.name_test)
name_fn <- `!!`(name_fn)
reported <- `!!`(.reported)
name_class <- `!!`(.name_class)
name_key_result <- `!!`(.name_key_result)
args_disabled <- `!!`(.args_disabled)
fn <- `!!`(.fn)
# First, before anything reads columns off `data`:
data <- as_tibble_input(data)
data <- absorb_key_args(data, reported)
check_args_disabled(args_disabled)
check_factory_dots(fn, name_fn, ...)
check_args_by_row_single(
`!!`(args_by_row_fn),
list(...),
name_fn,
"Sequence"
)
# `include_reported` is checked by `seq_disperse()`, and so is
# `dispersion`, but only if there is a case to disperse:
check_flag(include_consistent)
check_dispersion(
dispersion,
"Each value is a number of steps up and down from a reported value, \\
on the level of its last decimal place."
)
# A missing `digits_*` argument is left out, as the helpers above are, so
# that `fn()` raises its own error about it. `mget()` would force the
# promise and fail with R's generic message when a wrapper passes it on:
digits_vals <- list()
for (arg_digits in `!!`(digits_args_names)) {
if (!eval(call("missing", as.name(arg_digits)))) {
# As integer, since the step between dispersed values is
# `10^-digits`:
digits_vals[arg_digits] <- arg_digits |>
get() |>
as_integer_if_lossless() |>
list()
}
}
# `name_test` is required: without it, cli fails to evaluate the message
# of `check_consistency_not_in_colnames()`:
check_mapper_input_colnames(data, reported, name_test, name_key_result)
# Test the reported values. What `fn()` records about the call, such as
# `rounding`, applies to the re-tests below as well, so it is passed on to
# the output. The input's column names tell the result columns apart
# from the rest of `data` below:
cols_input <- colnames(data)
data <- do.call(
fn,
c(list(data), digits_vals, helper_vals, setting_vals, list(...))
)
meta_fn <- attr(data, "scrutiny", exact = TRUE)
args_fn <- scrutiny_args(data)
# The `digits_*` values that `fn()` tested, one per row, which may have
# come from columns of `data`. Each sets the decimal level that its row's
# value is dispersed on:
for (digits_name in `!!`(digits_args_names)) {
if (digits_name %in% colnames(data)) {
digits_vals[[digits_name]] <- data[[digits_name]]
}
}
# Mapper and sequence mapper must have the same `.name_key_result`. Catch
# a mismatch here, not as a `NULL` further down:
check_key_result_col(data, name_key_result, name_fn)
# What `fn()` tested: the key columns, helper columns such as
# `items_averaged`, and the `digits_*` columns, all left of the key
# result:
values_reported <- as.list(data)[
seq_len(match(name_key_result, colnames(data)) - 1L)
]
# The columns that the output has, whatever is dispersed: the input to
# the test, i.e. everything left of the key result column, and the
# columns `fn()` added. Other columns of `data` play no role in the test
# and are dropped, as the re-tests drop them:
cols_data <- colnames(data)
is_tested <- seq_along(cols_data) <= match(name_key_result, cols_data)
is_result <- !cols_data %in% cols_input
is_kept <- (is_tested | is_result) &
!cols_data %in% c("diff_var", "case", "var")
template <- data[0L, is_kept]
# Like `dplyr::filter(data, !consistency)`, but much faster. `which()`
# drops the `NA` of an undecidable case, which has no values to disperse;
# with `include_consistent`, too, where `seq_disperse()` would fail on
# it. `cases` are row numbers in the input data:
results <- data[[name_key_result]]
cases <- which(if (include_consistent) !is.na(results) else !results)
data <- data[cases, ]
# A case decided with its `digits_*` value missing has no decimal level
# to disperse on:
for (digits_name in names(digits_vals)) {
digits_cases <- rep_len(digits_vals[[digits_name]], nrow(data))
if (anyNA(digits_cases)) {
cases_na <- cases[is.na(digits_cases)]
abort_in_export(
"`{(digits_name)}` is missing in a case to disperse.",
"x" = "It is `NA` in row{?s} {cases_na} of `data`.",
"i" = "Sequence mappers disperse each value on the decimal level \
given by `{(digits_name)}`."
)
}
}
# With no variable, nothing would be dispersed, and the warning would name
# a variable "``":
if (length(var) == 0L) {
abort_in_export(
"`var` must name at least one column.",
"i" = "These are {wrap_in_backticks(reported)}."
)
}
# Only key columns are dispersed; `items_averaged`, for one, is not a
# rounded value:
if (!all(var %in% reported)) {
abort_in_export(
"`var` must only name the reported columns.",
"x" = "It includes {wrap_in_backticks(setdiff(var, reported))}.",
"i" = "These are {wrap_in_backticks(reported)}."
)
}
# A variable named twice would be dispersed twice, and every hit counted
# twice by `audit_seq()`:
if (anyDuplicated(var) > 0L) {
abort_in_export(
"`var` must not name a column more than once.",
"x" = "It names {wrap_in_backticks(unique(var[duplicated(var)]))} \
more than once."
)
}
# `var` itself is repeated per row later:
var_requested <- var
map_seq_proto <- function_map_seq_proto(
fn = fn,
dispersion = dispersion,
include_reported = include_reported,
name_key_result = name_key_result
)
# Forwarded to `fn()` via `map_seq_proto()`. Helper arguments are not
# among them: the re-tests read them from the columns that the first
# `fn()` call returned:
digits_cases <- lapply(digits_vals, function(vals) {
if (length(vals) > 1L) vals[cases] else vals
})
fn_args <- c(digits_cases, setting_vals, list(...))
# `out_min` and `out_max` are resolved per variable, since the dispersed
# variables have different domains. An explicit value applies to every
# variable:
var_bounds <- `!!`(.var_bounds)
# Not `purrr::map()`, which would wrap any error in an indexed-error
# context ("In index: 1.") that means nothing to the user:
out <- var |>
lapply(function(variable) {
limits <- resolve_var_bounds(
var = variable,
out_min = out_min,
out_max = out_max,
var_bounds = var_bounds,
args = args_fn
)
do.call(
map_seq_proto,
c(
list(
data = data,
.var = variable,
.cases = cases,
.out_min = limits$out_min,
.out_max = limits$out_max
),
fn_args
)
)
})
# A variable with no value to disperse from in any case has no output.
# `var` stays aligned with `out`, since it labels the rows below:
has_out <- !vapply(out, is.null, logical(1L))
out <- out[has_out]
var <- var[has_out]
# Cases to disperse from, but no values to disperse to, e.g. with
# `dispersion = 0` and `include_reported = FALSE`:
if (
length(out) > 0L &&
all(vapply(out, nrow, integer(1L), USE.NAMES = FALSE) == 0L)
) {
cli::cli_warn(c(
"!" = "No values to disperse to.",
"i" = "`dispersion`, `out_min`, and `out_max` leave no value \
around the reported ones."
))
}
if (length(out) == 0L) {
# An app that wants its own wording can catch the warning:
msg_setting <- "`include_consistent = TRUE`"
n_undecidable <- sum(is.na(results))
cli::cli_warn(c(
"!" = if (length(cases) > 0L) {
"No values to disperse from: {wrap_in_backticks(var_requested)} {?is/are} \\
missing in every case to disperse."
} else if (include_consistent) {
"No cases to disperse from."
} else {
"No inconsistent cases to disperse from."
},
"x" = if (n_undecidable > 0L) {
"{n_undecidable} case{?s} could not be tested, e.g. for a \\
missing value."
},
"i" = if (!include_consistent && length(cases) == 0L) {
"Try {msg_setting} to disperse from consistent cases, as well."
}
))
# Still with the usual columns, classes, and attribute, so that
# `audit_seq()` etc. accept it:
out <- template |>
tibble::add_column(diff_var = integer(0L), case = integer(0L)) |>
list()
var <- character(0L)
}
# One `var` string per row of `out`:
nrow_out <- vapply(out, nrow, integer(1L), USE.NAMES = FALSE)
var <- rep(var, nrow_out)
`!!!`(code_bind_cols)
# The same columns in the same order for every call. A variable with no
# dispersed rows was tested on no rows, which leaves out the columns
# unpacked from the results, such as `reason`, and binding takes the
# order of the first piece:
for (col in setdiff(colnames(template), colnames(out))) {
out[[col]] <- vctrs::vec_init(template[[col]], nrow(out))
}
out <- out[union(colnames(template), colnames(out))]
# A `digits_*` column per `digits_*` argument given, for
# `grim_plot_grid()` and the like. Counting decimal places in the numeric
# values would be unreliable: trailing zeros are lost. If such an
# argument has a default and was not given, `fn()`'s output decides
# whether there is a column.
for (digits_arg in names(digits_vals)) {
vals <- digits_vals[[digits_arg]]
out[[digits_arg]] <- if (length(vals) > 1L) {
vals[out$case]
} else {
rep_len(vals, nrow(out))
}
}
out <- out |>
dplyr::relocate(
dplyr::any_of(`!!`(digits_args_names)),
.before = dplyr::all_of(name_key_result)
)
out <- out |>
add_class(c(
"scrutiny_map_seq",
class_name_test(name_test, "_map_seq")
))
if (!is.null(name_class)) {
out <- out |>
add_class(name_class)
}
# Settings for functions downstream: those of the initial `fn()` call,
# set here rather than left to survive the binding above, then those of
# this call, such as `var`, which `audit_seq()` needs when there are no
# rows to read it off. Then:
# - `results_reported`: the verdict of every input row, which
# `audit_seq()` reports for each case without re-testing.
# - `name_key_result`: `audit_seq()` has no other way to learn it.
# - `values_reported`: the tested columns of the input, so that output of
# calls on different data can't be combined, which would number two
# cases as one (see `R/bind-rows.R`).
meta_fn$settings <- dplyr::bind_rows(
meta_fn$settings,
new_settings(
list(
var = var_requested,
dispersion = dispersion,
out_min = out_min,
out_max = out_max,
include_reported = include_reported,
include_consistent = include_consistent
),
`!!`(defaults_seq),
`!!`(name_mapper(.name_test, "_map_seq"))
)
)
attr(out, "scrutiny") <- c(
meta_fn,
list(
results_reported = results,
name_key_result = name_key_result,
values_reported = values_reported,
# The rows of each case's dispersion of each variable. Fewer in a
# piece of this output, as from `filter()`, means some were removed,
# whose hits `audit_seq()` can't know; none here means `out_min` or
# `out_max` left none:
rows_dispersed = count_rows_by(out$case, out$var)
)
)
# `rename = FALSE`: `fn()` already named the column, so only the
# list-column-to-logical half of this code applies here.
`!!!`(write_code_col_key_result(.name_key_result, rename = FALSE))
}),
# The body calls internal helpers, so the manufactured function needs an
# environment inheriting from scrutiny's namespace. `rlang::env()` creates a
# child of the present execution environment, which does.
env = rlang::env()
)
# --- End of the manufactured function, `fn_out()` ---
# The body is spliced from code blocks that keep their source references if
# the package is installed with `R_KEEP_PKG_SOURCE=yes`. These no longer
# match the statements, which crashed `codetools` in `R CMD check`:
fn_out <- utils::removeSource(fn_out)
# After the `digits_*` arguments, so that the signature starts the same way
# as the basic mapper's:
insert_key_args(
fn_out,
.reported,
insert_after = 1L + length(digits_args_names)
)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.