| Title: | A Declarative Interface for Statistical Inference |
|---|---|
| Description: | A declarative interface for statistical inference built on the S7 object system. The layouts of the statistical inference are described using expressive variable mappers, null hypotheses are stated as mathematical expressions over population parameters, and estimation is deferred until explicitly requested. Supports estimation method involving hypothesis testing and model-based inference with an extensible variant system for registering custom estimation methods. |
| Authors: | Joshua Marie [aut, cre], Antoine Soetewey [aut] (ORCID: <https://orcid.org/0000-0001-8159-0804>) |
| Maintainer: | Joshua Marie <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.0.9000 |
| Built: | 2026-09-21 11:44:05 UTC |
| Source: | https://github.com/s7-stats/statim |
These are developer-interface functions intended for package authors
extending the statim framework with new model types.
add_stat_define() registers a new stat_define() for a stat function,
enabling it to handle a previously unsupported variable mapper <var_id>.
Registering a model type that already exists — whether baked-in or
previously registered — is an error.
remove_stat_define() removes a previously registered "user"-originated
entry. "package"-scoped entries are self-cleaning via purge_stat_defines()
called in the registering package's .onUnload().
add_stat_define( stat_fn, model_type, impl, compatible_params = list(), origin = c("user", "package"), .pkg = NULL ) remove_stat_define(stat_fn, model_type)add_stat_define( stat_fn, model_type, impl, compatible_params = list(), origin = c("user", "package"), .pkg = NULL ) remove_stat_define(stat_fn, model_type)
stat_fn |
A test or model function built with |
model_type |
An S7 |
impl |
An |
compatible_params |
A list of param S7 classes (e.g. |
origin |
One of |
.pkg |
The registering package name. Required when |
NULL, invisibly.
Registrations have two scopes:
"user"-scoped entries live for the duration of the R session (or
until explicitly removed with remove_stat_define()). Use this for
interactive work or in scripts.
"package"-scoped entries are intended for package authors who ship
extensions to statim. They must be registered in .onLoad() and
cleaned up in .onUnload() via purge_stat_defines(). This keeps the
registry tidy when the extending package is unloaded.
To ship an extension as a package, register in zzz.R (or any file loaded
early):
.onLoad = function(libname, pkgname) {
statim::add_stat_define(
P_TEST,
my_var_id,
impl = agendas(
base = baseline(
fn = function(.proc, .p = 0.5, .alt = "two.sided", .ci = 0.95) {
# your implementation
}
)
),
compatible_params = list(PI),
origin = "package",
.pkg = pkgname
)
}
.onUnload = function(libpath) {
statim::purge_stat_defines("yourpackage")
}
The .pkg = pkgname argument is how statim knows which package owns
the entry. Without it, origin = "package" is an error. Never hard-code
the string yourself — always forward the pkgname R passes to .onLoad().
stat_define(), agendas(), remove_stat_define(),
purge_stat_defines()
# Session-scoped registration (interactive use or scripts) mt = S7::new_class("my_var", parent = var_id) add_stat_define( P_TEST, mt, impl = agendas( base = baseline( fn = function(.proc, .value = 1) list(value = .value) ) ) ) # Clean up when done remove_stat_define(P_TEST, mt)# Session-scoped registration (interactive use or scripts) mt = S7::new_class("my_var", parent = var_id) add_stat_define( P_TEST, mt, impl = agendas( base = baseline( fn = function(.proc, .value = 1) list(value = .value) ) ) ) # Clean up when done remove_stat_define(P_TEST, mt)
These are developer-interface functions intended for package authors
extending the statim framework with new method variants.
add_variant() is used as the left-hand side of the %<-% operator
to register a variant() for a stat function and model type.
"default" is frozen and cannot be added.
remove_variant() removes a previously registered "user"-originated
variant. "package"-level entries are self-cleaning: they exist for the
duration the registering package is loaded and vanish when it is unloaded.
add_variant(obj, model_type, name, origin = c("user", "package")) remove_variant(obj, model_type, name)add_variant(obj, model_type, name, origin = c("user", "package")) remove_variant(obj, model_type, name)
obj |
A test or model function built with |
model_type |
An S7 |
name |
A string naming the variant to add. |
origin |
One of |
An add_variant_call object, consumed by %<-%.
stat_define(), variant(), agendas(), model_processor()
# Add a bootstrap variant for x_by (user level). # .proc$x_data[[1]] is the response vector; .proc$group_data is the # grouping data frame. See ?model_processor for all available keys. add_variant(T_TEST, x_by, "another_boot") %<-% variant( fn = function(.proc, .n = 1000L) { x = .proc$x_data[[1]] grp = as.character(.proc$group_data[[1]]) lvls = unique(grp) x1 = x[grp == lvls[[1]]] x2 = x[grp == lvls[[2]]] boot_fn = function(d, i) mean(d[i, 1]) - mean(d[i, 2]) b = boot::boot(data.frame(x1, x2), boot_fn, R = .n) boot::boot.ci(b, type = "perc") } ) # Remove it, returning to the original slate remove_variant(T_TEST, x_by, "another_boot") # Package level (inside .onLoad()) add_variant(T_TEST, x_by, "another_boot", origin = "package") %<-% variant( fn = function(.proc, .n = 1000L) { ... } )# Add a bootstrap variant for x_by (user level). # .proc$x_data[[1]] is the response vector; .proc$group_data is the # grouping data frame. See ?model_processor for all available keys. add_variant(T_TEST, x_by, "another_boot") %<-% variant( fn = function(.proc, .n = 1000L) { x = .proc$x_data[[1]] grp = as.character(.proc$group_data[[1]]) lvls = unique(grp) x1 = x[grp == lvls[[1]]] x2 = x[grp == lvls[[2]]] boot_fn = function(d, i) mean(d[i, 1]) - mean(d[i, 2]) b = boot::boot(data.frame(x1, x2), boot_fn, R = .n) boot::boot.ci(b, type = "perc") } ) # Remove it, returning to the original slate remove_variant(T_TEST, x_by, "another_boot") # Package level (inside .onLoad()) add_variant(T_TEST, x_by, "another_boot", origin = "package") %<-% variant( fn = function(.proc, .n = 1000L) { ... } )
agendas() is the container for all implementations of a procedure.
Requires exactly one baseline() and accepts any number of named
variant() objects.
agendas(base, ...)agendas(base, ...)
base |
A |
... |
Named |
An agendas S3 object.
baseline(), variant(), stat_define()
anova() computes an incremental F-test across two or more fitted linear
models. It dispatches on four input types:
anova(object, ..., test = "F")anova(object, ..., test = "F")
object |
A |
... |
Additional |
test |
A string. One of |
An object of class S7_external_generic of length 4.
A multi_lazy from write_models() |> prepare_model().
An anova_lazy from write_models() |> prepare_model() (legacy path,
kept for backward compatibility).
One or more model_lazy objects from prepare_model().
One or more cld_exec objects from conclude().
A cld_anova object, invisibly.
write_models(), prepare_model(), conclude()
# via write_models() LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75, f4 = sr ~ pop15 + pop75 + dpi, f5 = sr ~ pop15 + pop75 + dpi + ddpi ) |> prepare_model(LINEAR_REG) |> anova() # via model_lazy mod1 = LifeCycleSavings |> define_model(sr ~ 1) |> prepare_model(LINEAR_REG) mod2 = LifeCycleSavings |> define_model(sr ~ pop15) |> prepare_model(LINEAR_REG) anova(mod1, mod2) # via conclude() mod1 = LifeCycleSavings |> define_model(sr ~ 1) |> prepare_model(LINEAR_REG) |> conclude() mod2 = LifeCycleSavings |> define_model(sr ~ pop15) |> prepare_model(LINEAR_REG) |> conclude() anova(mod1, mod2) anova(mod1, mod2, test = "LRT")# via write_models() LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75, f4 = sr ~ pop15 + pop75 + dpi, f5 = sr ~ pop15 + pop75 + dpi + ddpi ) |> prepare_model(LINEAR_REG) |> anova() # via model_lazy mod1 = LifeCycleSavings |> define_model(sr ~ 1) |> prepare_model(LINEAR_REG) mod2 = LifeCycleSavings |> define_model(sr ~ pop15) |> prepare_model(LINEAR_REG) anova(mod1, mod2) # via conclude() mod1 = LifeCycleSavings |> define_model(sr ~ 1) |> prepare_model(LINEAR_REG) |> conclude() mod2 = LifeCycleSavings |> define_model(sr ~ pop15) |> prepare_model(LINEAR_REG) |> conclude() anova(mod1, mod2) anova(mod1, mod2, test = "LRT")
auto_gauge() is the protocol generic for computing effect-size
quantities from result objects produced by fn in baseline() and
variant(). It is called automatically by gauge() when the result
stored in cld_exec@data is a class_stat_infer subclass.
auto_gauge(x, ...)auto_gauge(x, ...)
x |
A |
... |
Currently unused. Passed to the dispatched method. |
Register a method on your output class to participate:
S7::method(auto_gauge, my_test_result) = function(x, ...) {
tibble::tibble(metric = "cohens_d", value = ...)
}
A variant whose fn returns the same result class as baseline
inherits auto_gauge() for free via S7's parent chain.
A tibble with metric and value columns, one row per
effect-size quantity.
gauge(), making_gauge(), method_gauge(), class_stat_infer
auto_predict() is the protocol generic for producing predictions from
result objects produced by fn in baseline() and variant(). It is
called automatically by predict() when the result stored in
cld_exec@data is a class_stat_infer subclass.
auto_predict(x, new_data = NULL, ...)auto_predict(x, new_data = NULL, ...)
x |
A |
new_data |
A data frame. |
... |
Passed to the dispatched method. Methods typically accept a
|
Register a method on your output class to participate:
S7::method(auto_predict, my_model_result) = function(x, new_data = NULL, ...) {
tibble::tibble(.pred = ...)
}
A variant whose fn returns the same result class as baseline
inherits auto_predict() for free via S7's parent chain.
A data frame with at minimum a .pred column.
predict(), making_predict(), method_predict(), class_stat_infer
auto_tidy() is the protocol generic for tidying result objects produced
by fn in baseline() and variant(). It is called automatically by
tidy() when the result stored in cld_exec@data is a class_stat_infer
subclass.
auto_tidy(x, ...)auto_tidy(x, ...)
x |
A class_stat_infer subclass object, typically |
... |
Currently unused. Passed to the dispatched method. |
Register a method on your output class to participate in the protocol:
example_out = S7::new_class("example_out", parent = class_stat_infer)
S7::method(auto_tidy, example_out) = function(x, ...) {
tibble::tibble(...)
}
When a variant's fn returns the same output class as baseline, it
inherits auto_tidy() automatically via S7's parent chain. When it
returns a subclass, it can override selectively:
new_boot_class = S7::new_class("new_boot_class", parent = example_out)
# override only for boot
# everything else inherited from `example_out`
S7::method(auto_tidy, new_boot_class) = function(x, ...) {
tibble::tibble(...)
}
If no auto_tidy() method is found and no making_tidy() entry exists,
tidy() falls back to an informative error.
A tibble.
tidy(), making_tidy(), method_tidy(), class_stat_infer
baseline() declares the default implementation of a statistical procedure.
It is always the default and is the only implementation reachable on the
eager path.
baseline(fn, print = NULL, claim_parser = NULL)baseline(fn, print = NULL, claim_parser = NULL)
fn |
A function whose first argument must be
Try run this to explore the structure: Additional named arguments are user-supplied statistical parameters
(e.g. baseline(
fn = function(.proc, .mu = 0, .ci = 0.95) {
# ...
<your-own-class>(...) # return a class_stat_infer subclass
}
)
When |
print |
A function with signature |
claim_parser |
A |
A baseline S7 object.
variant(), agendas(), stat_define(), model_processor(),
map_claim(), class_stat_infer, auto_tidy()
Decomposes the hypothesis into a named numeric vector of coefficients,
one per param_obj term, plus the hypothesized scalar value and operator.
claim_contrast_coefs(claim, filter = NULL)claim_contrast_coefs(claim, filter = NULL)
claim |
A |
filter |
Optional. The name of a conditioning slot (e.g. |
A list with fields coefs, scalar, and op.
Rearranges a hypothesis of the form c * PARAM + d == scalar by moving
all numeric terms to the right-hand side. Unlike claim_contrast_coefs(),
this does not require or validate a linear combination — it is suitable for
single-parameter claims involving any param_obj subclass (e.g. MU(),
PI(), RHO()).
claim_scalar(claim, solve_coef = FALSE)claim_scalar(claim, solve_coef = FALSE)
claim |
A |
solve_coef |
Logical. If |
A list with fields:
coefsNamed numeric vector of length 1: the coefficient c on
the parameter term.
scalarNumeric. The resolved scalar value after rearrangement.
opCharacter. The (possibly flipped) relational operator.
An S7 generic dispatched on the variable mapper <var_id> class. Called automatically inside
state_null() after the compatible-param guard. Implement a method for any
new var_id subclass you define.
validate_claim_vars(var_id, processed, claims, ...) check_param_nodes(claims, x_vars, by_vars) validate_one_param_node(node, ...) check_x_and_given(x_quo, given_quo, x_vars, by_vars, cls_name)validate_claim_vars(var_id, processed, claims, ...) check_param_nodes(claims, x_vars, by_vars) validate_one_param_node(node, ...) check_x_and_given(x_quo, given_quo, x_vars, by_vars, cls_name)
var_id |
A <var_id> object (usually carried by |
processed |
The processed list from |
claims |
A |
... |
Currently unused. |
x_vars |
A character vector of declared x-variable names, or |
by_vars |
A character vector of declared grouping variable names, or
|
node |
A |
x_quo |
A quosure holding the |
given_quo |
A quosure holding the |
cls_name |
A string naming the param class, used in error messages. |
check_param_nodes() is the shared walker used by all built-in
validate_claim_vars() methods. It collects every param_obj node,
runs validate_one_param_node() on each, deduplicates errors, and aborts
with a consolidated message. Call this inside your own
validate_claim_vars() method rather than re-implementing the walking and
accumulation logic.
validate_one_param_node() is an S7 generic dispatched on param_obj.
Returns a character vector of error strings — empty if valid. The default
method on param_obj returns character(0), so unknown subclasses pass
through safely. Implement a method for any new param_obj subclass whose
slots should be checked against the model's declared variables.
check_x_and_given() is the standard building block for
validate_one_param_node() methods on param_obj subclasses that follow
the MU(x, given) slot convention. It checks an x quosure against
x_vars and a given quosure against by_vars.
invisible(NULL), or aborts with a consolidated error.
By default, unknown variable mapper <var_id> subclasses pass through without validation.
To add validation for a new var_id subclass, implement a method and
delegate to check_param_nodes():
S7::method(validate_claim_vars, <var_id>) = function(var_id, processed, claims) {
check_param_nodes(
claims,
x_vars = names(processed$x_data),
by_vars = names(processed$group_data)
)
}
validate_one_param_node for a new param classFor a subclass with x and given slots, delegate to
check_x_and_given():
S7::method(validate_one_param_node, MY_PARAM) = function(node, x_vars, by_vars) {
check_x_and_given(node@x, node@given, x_vars, by_vars, "MY_PARAM")
}
For a subclass with two variable slots (like RHO()):
S7::method(validate_one_param_node, MY_PARAM) = function(node, x_vars, by_vars) {
errors = character(0)
for (slot_quo in list(node@x, node@y)) {
lbl = rlang::as_label(slot_quo)
if (!is.null(x_vars) && !lbl %in% x_vars) {
errors = c(errors, cli::format_inline(
"Unknown variable {.val {lbl}} in {.cls MY_PARAM}. ",
"Model declares x-variable{?s}: {.and {.val {x_vars}}}."
))
}
}
errors
}
state_null(), MU(), RHO(), PI(), param_obj(), var_id()
An S7 class produced by COR_TEST using rel() and <formula> as the variable mapper <var_id>.
Not constructed manually, use the "grammar interface" instead.
Inherits from class_stat_infer, so auto_tidy() dispatches on it
automatically. Downstream packages can use it as a parent in
S7::new_class().
Slots (populated automatically by COR_TEST):
ind_vars: name of the independent variables.
resp_vars: name of the response / dependent variables.
estimate: the estimated correlation coefficient.
statistic: t-statistic.
df: degrees of freedom.
p_val: p-value.
lower_ci: lower confidence bound.
upper_ci: upper confidence bound.
ci_level: confidence level, e.g. 0.95.
Both rel() and <formula>'s default (base) return a class_corr_two, so different
models shares both auto_tidy() and print() for free.
COR_TEST, auto_tidy(), class_stat_infer
An S7 class produced by GLM pipelines. Not constructed manually —
use define_model() |> prepare_model(GLM) |> conclude() instead.
Inherits from anova_able, so it participates in anova() directly.
Downstream packages can use it as a parent in S7::new_class().
Constructor arguments (populated automatically by GLM):
terms: model terms object.
df_residual: residual degrees of freedom.
deviance: scalar deviance.
dispersion: scalar dispersion parameter.
family: string naming the error family, e.g. "binomial".
link: string naming the link function, e.g. "logit".
null_deviance: scalar deviance of the intercept-only model.
aic: scalar AIC.
logLik: scalar log-likelihood of the fitted model.
null_logLik: scalar log-likelihood of the intercept-only model.
beta: named numeric vector of coefficient estimates.
std_beta: named numeric vector of coefficient standard errors.
actual: numeric vector of the original values on the response scale.
fitted: numeric vector of fitted values on the response scale.
vcov: variance-covariance matrix of the coefficients, e.g.
stats::vcov(fit). Required for predict() with interval.
x_mat: model matrix stored as a flat numeric vector via
as.numeric(stats::model.matrix(fit)). Required for predict().
x_levels: factor levels used when fitting, via
stats::.getXlevels(fit$terms, stats::model.frame(fit)). Required
for predict() on new data with factor predictors.
The following are computed automatically and do not need to be supplied:
statistic: per-coefficient test statistics (beta / std_beta).
p_value: per-coefficient two-sided p-values. Uses a z-test when
family is "binomial" or "poisson" (fixed dispersion), and a
t-test against df_residual otherwise (estimated dispersion).
coefficients: tibble with columns term, estimate, std_error,
statistic, p_value.
fit_summary: tibble with columns family, link, null_deviance,
deviance, df_residual, aic, n_obs.
An S7 object of class glm_object holding the fitted GLM's
terms, coefficients, dispersion, and family information. Not constructed
manually; populated internally by GLM.
predict() on a class_glm_object accepts:
new_data: A data frame of new predictors. NULL (the default)
returns fitted values and response-based truth for the training data.
type: One of "response" (default, back-transformed through the
inverse link) or "link" (linear predictor scale).
interval: One of "none" (default) or "confidence".
Prediction intervals are not available, since GLMs have no closed-form
analogue of OLS prediction error.
level: Confidence level for the interval. Default 0.95.
# Inheriting from class_glm_object in a downstream package: my_glm = S7::new_class( "my_glm", parent = class_glm_object ) # Populating class_glm_object from a fitted glm (as done internally): fit = glm(am ~ wt + hp, data = mtcars, family = binomial()) s = summary(fit) fam = fit$family$family obj = class_glm_object( terms = fit$terms, df_residual = fit$df.residual, deviance = fit$deviance, dispersion = if (fam %in% c("binomial", "poisson")) 1 else s$dispersion, family = fam, link = fit$family$link, null_deviance = fit$null.deviance, aic = fit$aic, beta = coef(s)[, 1], std_beta = coef(s)[, 2], actual = unname(fit$y), fitted = unname(fit$fitted.values), vcov = vcov(fit), x_mat = as.numeric(model.matrix(fit)), x_levels = .getXlevels(fit$terms, model.frame(fit)) ) obj@coefficients obj@fit_summary# Inheriting from class_glm_object in a downstream package: my_glm = S7::new_class( "my_glm", parent = class_glm_object ) # Populating class_glm_object from a fitted glm (as done internally): fit = glm(am ~ wt + hp, data = mtcars, family = binomial()) s = summary(fit) fam = fit$family$family obj = class_glm_object( terms = fit$terms, df_residual = fit$df.residual, deviance = fit$deviance, dispersion = if (fam %in% c("binomial", "poisson")) 1 else s$dispersion, family = fam, link = fit$family$link, null_deviance = fit$null.deviance, aic = fit$aic, beta = coef(s)[, 1], std_beta = coef(s)[, 2], actual = unname(fit$y), fitted = unname(fit$fitted.values), vcov = vcov(fit), x_mat = as.numeric(model.matrix(fit)), x_levels = .getXlevels(fit$terms, model.frame(fit)) ) obj@coefficients obj@fit_summary
An S7 class produced by LINEAR_REG pipelines. Not constructed manually —
use define_model() |> prepare_model(LINEAR_REG) |> conclude() instead.
Inherits from anova_able, so it participates in anova() directly.
Downstream packages can use it as a parent in S7::new_class().
Constructor arguments (populated automatically by LINEAR_REG):
terms: model terms object.
df_residual: residual degrees of freedom.
deviance: residual sum of squares (RSS).
dispersion: mean squared error (MSE), i.e. rss / df_residual.
family: always "gaussian" for OLS.
fitted: numeric vector of fitted values.
residuals: numeric vector of model residuals.
beta: named numeric vector of coefficient estimates.
std_beta: named numeric vector of coefficient standard errors.
x_mat: model matrix stored as a flat numeric vector via
as.numeric(stats::model.matrix(fit)). Required for single-model
anova(); omit only if Type I ANOVA is not needed.
The following are computed automatically and do not need to be supplied:
statistic: per-coefficient t-statistics (beta / std_beta).
p_value: per-coefficient two-sided p-values.
coefficients: tibble with columns term, estimate, std_error,
statistic, p_value.
fit_summary: two-column tibble (statistic, value) with R-squared,
adjusted R-squared, sigma, n, residual df, F-statistic, df1, df2, and
F p-value.
An S7 object of class lm_object holding the fitted model's
terms, coefficients, residuals, and dispersion. Not constructed manually;
populated internally by the linear regression pipeline.
class_lm_object supports two anova() modes:
Single model — Type I (sequential) ANOVA. Each term is tested
against the model containing all preceding terms. Requires x_mat
to be populated.
Multiple models — incremental F-test or LRT across nested models.
Uses @deviance and @df_residual only; x_mat is not needed.
predict() on a class_lm_object accepts:
new_data: A data frame of new predictors. NULL (the default)
returns fitted values and residual-based truth for the training data.
interval: One of "none" (default), "confidence", or
"prediction". Both are available for every class_lm_object, since
family is always "gaussian" for OLS fits.
level: Confidence level for the interval. Default 0.95.
# Inheriting from class_lm_object in a downstream package: my_lm = S7::new_class( "my_lm", parent = statim::class_lm_object ) # Populating class_lm_object from a fitted lm (as done internally): fit = lm(dist ~ speed, data = cars) coef_tbl = summary(fit)$coefficients rss = sum(fit$residuals^2) df_res = fit$df.residual obj = class_lm_object( terms = fit$terms, fitted = unname(fit$fitted.values), residuals = unname(fit$residuals), beta = coef_tbl[, 1], std_beta = coef_tbl[, 2], df_residual = df_res, deviance = rss, dispersion = rss / df_res, family = "gaussian", x_mat = as.numeric(stats::model.matrix(fit)) ) obj@coefficients obj@fit_summary# Inheriting from class_lm_object in a downstream package: my_lm = S7::new_class( "my_lm", parent = statim::class_lm_object ) # Populating class_lm_object from a fitted lm (as done internally): fit = lm(dist ~ speed, data = cars) coef_tbl = summary(fit)$coefficients rss = sum(fit$residuals^2) df_res = fit$df.residual obj = class_lm_object( terms = fit$terms, fitted = unname(fit$fitted.values), residuals = unname(fit$residuals), beta = coef_tbl[, 1], std_beta = coef_tbl[, 2], df_residual = df_res, deviance = rss, dispersion = rss / df_res, family = "gaussian", x_mat = as.numeric(stats::model.matrix(fit)) ) obj@coefficients obj@fit_summary
An S7 class produced by P_TEST pipelines using prop() as the model
ID. Not constructed manually — use the pipeline instead.
Inherits from class_stat_infer, so auto_tidy() dispatches on it
automatically. Downstream packages can use it as a parent in
S7::new_class().
Slots (populated automatically by P_TEST):
x: number of successes (input).
n: number of trials (input).
estimate: observed proportion (x / n).
statistic: test statistic. The count x for the default binomial;
the chi-squared value for "prop".
p_val: p-value.
lower_ci: lower confidence bound.
upper_ci: upper confidence bound.
ci_level: confidence level, e.g. 0.95.
An S7 object of class p_test, with the properties listed in
Details. Not constructed manually; returned by P_TEST pipelines.
Both default and prop return a class_p_test, so auto_tidy() and
print() are inherited by prop for free.
P_TEST, auto_tidy(), class_stat_infer
class_stat_infer is the base abstract S7 class for all result objects returned
by fn in baseline() and variant(). Concrete result classes like
class_lm_object inherit from it.
class_stat_infer()class_stat_infer()
Inheriting from class_stat_infer is the contract that enables automatic
dispatch for auto_tidy(), and future auto_plot() and auto_export()
generics, without any manual registration via making_tidy().
An S7 abstract class generator. class_stat_infer cannot be
instantiated directly, so calling it raises an error. It exists only as a
parent class for the concrete result classes described in the Class
hierarchy section above.
Inheriting from class_stat_infer is the contract that enables automatic
dispatch for auto_tidy(), and future auto_plot() and auto_export()
generics, without any manual registration via making_tidy().
When fn in baseline() or variant() returns a class_stat_infer
subclass, tidy() calls auto_tidy() on it automatically. Register a
method on your result class to participate:
example_out = S7::new_class("example_out", parent = class_stat_infer)
S7::method(auto_tidy, example_out) = function(x, ...) {
# return something
}
A variant whose fn returns the same result class as baseline inherits
all auto_*() methods for free via S7's parent chain. A variant that
returns a subclass overrides only what it needs — everything else
inherits automatically:
my_result_boot = S7::new_class("my_result_boot", parent = my_result)
# only auto_tidy() differs
# all other auto_*() inherited from my_result
S7::method(auto_tidy, my_result_boot) = function(x, ...) {
tibble::tibble(...)
}
The built-in hierarchy is:
class_stat_infer
|-- anova_able
| `-- class_lm_object
`-- <your-own-output-class>
`-- <your-own-subclass>
Downstream packages can extend the hierarchy further by using any
class_stat_infer subclass as a parent in S7::new_class().
baseline(), variant(), auto_tidy(), class_lm_object
An S7 class produced by T_TEST pipelines using on() as the variable
mapper <var_id>. Not constructed manually — use the pipeline instead.
Inherits from class_stat_infer, so auto_tidy() dispatches on it
automatically. Downstream packages can use it as a parent in
S7::new_class().
Slots (populated automatically by T_TEST):
term: name of the tested variable.
estimate: sample mean.
true_mu: hypothesized mean as written in the claim. Falls back to
.mu when no state_null() claim is supplied.
statistic: t-statistic.
p_val: p-value.
lower_ci: lower confidence bound.
upper_ci: upper confidence bound.
ci_level: confidence level, e.g. 0.95.
An S7 object of class ttest_one, with the properties listed in
Details. Not constructed manually; returned by T_TEST pipelines.
Both base and multi return a class_ttest_one, so auto_tidy() and
print() are inherited by multi for free.
T_TEST, ttest-on, auto_tidy(), class_stat_infer
An S7 class produced by T_TEST pipelines using pairwise() as the
variable mapper <var_id>. Not constructed manually — use the pipeline instead.
Inherits from class_stat_infer, so auto_tidy() dispatches on it
automatically. Downstream packages can use it as a parent in
S7::new_class().
Slots (populated automatically by T_TEST):
var1: first variable in each pair.
var2: second variable in each pair.
est: mean difference per pair (or sample mean for one-sample mode).
df: degrees of freedom per pair.
t_stat: t-statistic per pair.
p_value: p-value per pair.
method_name: scalar string describing the test method, taken directly
from stats::t.test(). Must be length 1 — all pairs must share the
same method.
An S7 object of class ttest_pairwise, with the properties
listed in Details. Not constructed manually; returned by T_TEST
pipelines using pairwise().
When pairwise() uses direction = "eq", var1 and var2 are
identical (each variable tested against itself). print() detects this
and renders a diagonal-only matrix.
T_TEST, ttest-pairwise, auto_tidy(), class_stat_infer
An S7 class produced by T_TEST pipelines using x_by() as the variable mapper <var_id>.
Not constructed manually — use the pipeline instead.
Inherits from class_stat_infer, so auto_tidy() dispatches on it
automatically. Downstream packages can use it as a parent in
S7::new_class().
Slots (populated automatically by T_TEST):
group: name of the grouping variable.
estimate: mean difference (or linear contrast estimate).
t_stat: t-statistic.
df: degrees of freedom.
p_val: p-value.
lower_ci: lower confidence bound.
upper_ci: upper confidence bound.
ci_level: confidence level, e.g. 0.95.
An S7 object of class ttest_two, with the properties listed in
Details. Not constructed manually; returned by T_TEST pipelines.
Both the default (base) and contrast return a class_ttest_two, so
auto_tidy() and print() are inherited by contrast for free.
T_TEST, auto_tidy(), class_stat_infer
class_var_inform is the S7 output class returned by var_id_info().
model_type is derived automatically from the stored var_id object.
All other properties default to empty / unknown values, which are filled in
by registered var_id_info() methods for known subclasses.
An S7 object of class var_inform holding the Variable Mapper's
type, arguments, extracted variables, and registration status. Returned
by var_id_info(), not constructed manually.
conclude() is the terminal step of the pipeline. It resolves the
method variant, runs the implementation, and returns a cld_exec S7 object.
conclude(.x, ...)conclude(.x, ...)
.x |
A |
... |
Currently unused. |
A cld_exec S7 object with the following slots:
@dataThe raw return value of the fn defined in baseline()
or variant(). Its structure depends on the implementation — see the
documentation of the stat function (e.g. ?T_TEST) for what to expect.
@cld_metaA list of pipeline metadata:
$var_idThe Variable Mapper object passed to define_model().
$processedThe processed model output from model_processor().
The same object received as .proc inside the fn.
$stat_nameThe human-readable test or model name.
$methodThe variant name used. "default" when no via()
was called.
$data_nameThe name of the data frame, if resolvable.
The print argument of baseline() and variant() receives a cld_exec
object as x. Read your output from x@data:
baseline(
fn = function(.proc, .mu = 0) { ... },
print = function(x, ...) {
dat = x@data
# render dat
invisible(x)
}
)
Otherwise, when the base S7 class dispatches print() elsewhere, it is inherited
without writing print from baseline() / variant()
Prefer implementing auto_tidy() on your result class when fn returns
a class_stat_infer subclass. Use making_tidy() only when fn
intentionally returns a non-class_stat_infer object.
For example:
making_tidy(T_TEST, x_by) %<-% method_tidy(
default = function(.x, ...) {
dat = .x@data
# return a tibble
}
)
prepare_test(), prepare_model(), via(), model_processor(),
class_stat_infer, auto_tidy()
sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> conclude() sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> via("boot", n = 2000) |> conclude() mtcars |> define_model(rel(mpg, wt)) |> prepare_model(LINEAR_REG) |> conclude()sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> conclude() sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> via("boot", n = 2000) |> conclude() mtcars |> define_model(rel(mpg, wt)) |> prepare_model(LINEAR_REG) |> conclude()
COR_TEST() performs a correlation test for one-to-one variable
relationships. If COR_TEST is supplied within the lazy-loaded pipeline,
supply COR_TEST as a function i.e. prepare_test(.test = COR_TEST) call.
COR_TEST(.var_id = NULL, .data = NULL, ...)COR_TEST(.var_id = NULL, .data = NULL, ...)
.var_id |
A variable mapper |
.data |
A data frame. Only used on the standalone path. |
... |
Additional arguments passed to the implementation. See the Arguments section of each implementation page. |
A cld_exec object (in conclude()), or a test_spec object
when .var_id = NULL. The default correlation test class for most paths is
class_corr_two.
<var_id>sEach variable mapper <var_id> routes to a separate implementation. See the linked pages
for full argument lists, variants, and correlation test class details:
rel(): one-to-one correlation test. See details from cortest-rel.
<formula>: one-to-many correlation test. See details from cortest-formula.
cortest-rel, cortest-formula for per-implementation details.
class_corr_two for correlation test class slots.
via(), state_null(), conclude(), auto_tidy().
# eager COR_TEST(rel(speed, dist), cars) # grammatical syntax cars |> define_model(rel(speed, dist)) |> prepare_test(COR_TEST) |> conclude() cars |> define_model(speed ~ dist) |> prepare_test(COR_TEST) |> conclude() # Spearman suppressWarnings({ cars |> define_model(rel(speed, dist)) |> prepare_test(COR_TEST) |> via("spearman") |> conclude() }) # Custom Hypothesis Expression cars |> define_model(rel(speed, dist)) |> prepare_test(COR_TEST) |> state_null(RHO(speed, dist) >= 0.8) |> conclude()# eager COR_TEST(rel(speed, dist), cars) # grammatical syntax cars |> define_model(rel(speed, dist)) |> prepare_test(COR_TEST) |> conclude() cars |> define_model(speed ~ dist) |> prepare_test(COR_TEST) |> conclude() # Spearman suppressWarnings({ cars |> define_model(rel(speed, dist)) |> prepare_test(COR_TEST) |> via("spearman") |> conclude() }) # Custom Hypothesis Expression cars |> define_model(rel(speed, dist)) |> prepare_test(COR_TEST) |> state_null(RHO(speed, dist) >= 0.8) |> conclude()
display() prints the first n concluded models from an abstract S7
class, e.g. multi_exec, in full. Useful when conclude() has been called on a
write_models() pipeline and the default compressed print is not enough.
display(x, n = 3L, ...)display(x, n = 3L, ...)
x |
An object yield by |
n |
A positive integer. The number of models' output to display. Defaults
to |
... |
Currently unused. |
x, invisibly.
write_models(), conclude(), tidy()
LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75, f4 = sr ~ pop15 + pop75 + dpi, f5 = sr ~ pop15 + pop75 + dpi + ddpi ) |> prepare_model(LINEAR_REG) |> conclude() |> display(2)LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75, f4 = sr ~ pop15 + pop75 + dpi, f5 = sr ~ pop15 + pop75 + dpi + ddpi ) |> prepare_model(LINEAR_REG) |> conclude() |> display(2)
gauge() reports the standardized magnitude of an effect — Cohen's d,
partial eta-squared, odds ratio, and similar quantities — as distinct
from tidy()'s raw estimates and the p-value's significance verdict.
gauge(object, ...)gauge(object, ...)
object |
A |
... |
Passed to the dispatched method. |
A tibble with metric and value columns, one row per
effect-size quantity reported by the underlying result class.
Same two paths as tidy()/glance()/predict():
Path 1: auto_gauge() (preferred).
Called directly when cld_exec@data is a class_stat_infer subclass.
Path 2: making_gauge() registry (escape hatch).
Used when a variant's fn intentionally returns a non-class_stat_infer
object.
conclude(), auto_gauge(), making_gauge()
A modified GLM for {statim} pipeline passed through stats::glm().
GLM(.var_id = NULL, .data = NULL, ...)GLM(.var_id = NULL, .data = NULL, ...)
.var_id |
A variable mapper |
.data |
A data frame. Used when |
... |
Additional arguments passed to |
Additional arguments are passed to stats::glm(). The most important
is family, which controls the error distribution and link function
(e.g. stats::binomial(), stats::poisson()). Defaults to
stats::gaussian() when omitted.
A cld_exec object in a class_glm_object, or a model_spec
when .var_id = NULL.
# logistic regression mtcars |> define_model(am ~ wt + hp) |> prepare_model(GLM) |> update(family = binomial()) |> conclude() # model comparison via anova() mod1 = mtcars |> define_model(am ~ 1) |> prepare_model(GLM) |> update(family = binomial()) |> conclude() mod2 = mtcars |> define_model(am ~ wt) |> prepare_model(GLM) |> update(family = binomial()) |> conclude() mod3 = mtcars |> define_model(am ~ wt + hp) |> prepare_model(GLM) |> update(family = binomial()) |> conclude() anova(mod1, mod2, mod3)# logistic regression mtcars |> define_model(am ~ wt + hp) |> prepare_model(GLM) |> update(family = binomial()) |> conclude() # model comparison via anova() mod1 = mtcars |> define_model(am ~ 1) |> prepare_model(GLM) |> update(family = binomial()) |> conclude() mod2 = mtcars |> define_model(am ~ wt) |> prepare_model(GLM) |> update(family = binomial()) |> conclude() mod3 = mtcars |> define_model(am ~ wt + hp) |> prepare_model(GLM) |> update(family = binomial()) |> conclude() anova(mod1, mod2, mod3)
HTEST_FN() is a developer-interface constructor for user-facing test
functions like T_TEST(). It returns a function with a consistent
signature that routes to the correct implementation based on the variable mapper <var_id>
and method variant.
HTEST_FN(cls, defs, .name)HTEST_FN(cls, defs, .name)
cls |
A string naming the test class, e.g. |
defs |
A list of |
.name |
A string used as the test title in output. |
A function with signature function(.var_id, .data, ...).
MODEL_FN(), stat_define(), prepare_test(), via(), conclude()
inlines() is the multi-expression analogue of c() for inline data.
Where c(x1, x2) selects multiple variables or columns by name from a
data frame or the calling environment, inlines() accepts raw expressions
— vectors, function calls, or any R expression — and evaluates them
immediately at model definition time.
inlines(...)inlines(...)
... |
Named or unnamed expressions. If named, the supplied name becomes
the variable name in the processed output. Unnamed elements are
auto-named by their role and position: |
Use inlines() when your data does not live in a data frame. For a single
inline expression, use I() instead. Take note that inlines() does not
return an evaluated value, only a naked and unevaluated expression.
A named list of quosures. Intended for use inside variable mapper <var_id>
functions such as x_by() and rel(); not typically called on its own.
I() for a single inline expression, x_by(), rel(),
pairwise()
# Named inline expressions — names appear in output x_by( inlines(x1 = rnorm(30), x2 = rnorm(30)), I(grp = rep(c("a", "b"), each = 15)) ) # Unnamed — auto-named as xv1, xv2 under role "x" x_by( inlines(rnorm(30), rnorm(30)), I(rep(c("a", "b"), each = 15)) ) # Mixed — named elements keep their name, unnamed get auto-names x_by( inlines(x1 = rnorm(30), rnorm(30)), I(rep(c("a", "b"), each = 15)) ) # Contrast with c() — selects existing variables by name x1 = rnorm(30) x2 = rnorm(30) grp = rep(c("a", "b"), each = 15) x_by(c(x1, x2), grp)# Named inline expressions — names appear in output x_by( inlines(x1 = rnorm(30), x2 = rnorm(30)), I(grp = rep(c("a", "b"), each = 15)) ) # Unnamed — auto-named as xv1, xv2 under role "x" x_by( inlines(rnorm(30), rnorm(30)), I(rep(c("a", "b"), each = 15)) ) # Mixed — named elements keep their name, unnamed get auto-names x_by( inlines(x1 = rnorm(30), rnorm(30)), I(rep(c("a", "b"), each = 15)) ) # Contrast with c() — selects existing variables by name x1 = rnorm(30) x2 = rnorm(30) grp = rep(c("a", "b"), each = 15) x_by(c(x1, x2), grp)
define_model() captures a variable mapper <var_id> and optional data into a def_var
object that can be passed into prepare_test().
define_model(.x, ...)define_model(.x, ...)
.x |
A variable mapper |
... |
Currently unused. |
Two dispatch methods are available depending on how .x is supplied:
A "Variable Mapper" first: .x is a Variable Mapper or formula. Accepts data, a
data frame (defaults to parent.frame()).
DataFrame-first: .x is a data frame. Accepts to_analyze, a variable mapper
or formula, as the second argument.
A def_var S3 object containing var_id and processed.
# model-ID first define_model(x_by(extra, group), sleep) # data-frame first (pipe-friendly) sleep |> define_model(x_by(extra, group))# model-ID first define_model(x_by(extra, group), sleep) # data-frame first (pipe-friendly) sleep |> define_model(x_by(extra, group))
Fits an ordinary least squares linear regression model.
Accepts rel() or a formula as the variable mapper <var_id>.
LINEAR_REG(.var_id = NULL, .data = NULL, ...)LINEAR_REG(.var_id = NULL, .data = NULL, ...)
.var_id |
A variable mapper |
.data |
A data frame. Used when |
... |
Currently unused. |
The result is an class_lm_object, which satisfies the anova()
protocol and prints coefficients and model fit universally across
all engines and variants.
A cld_exec object containing a class_lm_object, or a model_spec
when .var_id = NULL.
# via rel() cars |> define_model(rel(speed, dist)) |> prepare_model(LINEAR_REG) |> conclude() # via formula cars |> define_model(dist ~ speed) |> prepare_model(LINEAR_REG) |> conclude() # write_models() pipeline LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75, f4 = sr ~ pop15 + pop75 + dpi, f5 = sr ~ pop15 + pop75 + dpi + ddpi ) |> prepare_model(LINEAR_REG) |> anova() # individual conclude(), compare after mod1 = LifeCycleSavings |> define_model(sr ~ 1) |> prepare_model(LINEAR_REG) |> conclude() mod2 = LifeCycleSavings |> define_model(sr ~ pop15) |> prepare_model(LINEAR_REG) |> conclude() anova(mod1, mod2)# via rel() cars |> define_model(rel(speed, dist)) |> prepare_model(LINEAR_REG) |> conclude() # via formula cars |> define_model(dist ~ speed) |> prepare_model(LINEAR_REG) |> conclude() # write_models() pipeline LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75, f4 = sr ~ pop15 + pop75 + dpi, f5 = sr ~ pop15 + pop75 + dpi + ddpi ) |> prepare_model(LINEAR_REG) |> anova() # individual conclude(), compare after mod1 = LifeCycleSavings |> define_model(sr ~ 1) |> prepare_model(LINEAR_REG) |> conclude() mod2 = LifeCycleSavings |> define_model(sr ~ pop15) |> prepare_model(LINEAR_REG) |> conclude() anova(mod1, mod2)
making_gauge() is the escape hatch for registering effect-size
methods when a variant's fn intentionally returns a non-
class_stat_infer object. When fn returns a class_stat_infer
subclass, implement auto_gauge() on the result class instead — no
registration needed.
making_gauge(obj, model_type)making_gauge(obj, model_type)
obj |
A stat function built with |
model_type |
An S7 variable mapper |
A making_gauge_call object, consumed by %<-%.
auto_gauge(), method_gauge(), class_stat_infer
# Only needed when fn returns a non-class_stat_infer object. # Prefer implementing auto_gauge() on your result class instead. making_gauge(T_TEST, x_by) %<-% method_gauge( default = function(.x, ...) { ... } )# Only needed when fn returns a non-class_stat_infer object. # Prefer implementing auto_gauge() on your result class instead. making_gauge(T_TEST, x_by) %<-% method_gauge( default = function(.x, ...) { ... } )
making_predict() is the escape hatch for registering predict methods
when a variant's fn intentionally returns a non-class_stat_infer
object. When fn returns a class_stat_infer subclass, implement
auto_predict() on the result class instead — no registration needed.
making_predict(obj, model_type)making_predict(obj, model_type)
obj |
A stat function built with |
model_type |
An S7 variable mapper |
A making_predict_call object, consumed by %<-%.
auto_predict(), method_predict(), class_stat_infer
# Only needed when fn returns a non-class_stat_infer object. # Prefer implementing auto_predict() on your result class instead. making_predict(LINEAR_REG, S7::class_formula) %<-% method_predict( default = function(.x, new_data = NULL, ...) { ... } )# Only needed when fn returns a non-class_stat_infer object. # Prefer implementing auto_predict() on your result class instead. making_predict(LINEAR_REG, S7::class_formula) %<-% method_predict( default = function(.x, new_data = NULL, ...) { ... } )
making_tidy() is the escape hatch for registering tidy methods when a
variant's fn intentionally returns a non-class_stat_infer object
(plain list, S3, S4, or R6). When fn returns a class_stat_infer
subclass, implement auto_tidy() on the result class instead — no
registration needed.
making_tidy(obj, model_type)making_tidy(obj, model_type)
obj |
A stat function built with |
model_type |
An S7 variable mapper |
A making_tidy_call object, consumed by %<-%.
auto_tidy(), method_tidy(), class_stat_infer
# Only needed when fn returns a non-class_stat_infer object. # Prefer implementing auto_tidy() on your result class instead. making_tidy(T_TEST, x_by) %<-% method_tidy( default = function(.x, ...) { ... }, boot = function(.x, ...) { ... } )# Only needed when fn returns a non-class_stat_infer object. # Prefer implementing auto_tidy() on your result class instead. making_tidy(T_TEST, x_by) %<-% method_tidy( default = function(.x, ...) { ... }, boot = function(.x, ...) { ... } )
map_claim() produces a parser function by mapping impl fn formal
names to resolver functions. Each resolver receives (claim, processed)
and returns the value for its argument. Resolvers that only need claim
can simply ignore processed.
map_claim(...)map_claim(...)
... |
Named resolver functions. Names must match formals of the
impl's |
Pass the result as claim_parser to baseline() or variant(). A
variant without a claim_parser simply does not support state_null();
conclude() raises an error if a claim was stated but the active variant
has none.
A function of class "map_claim" with signature
function(claim, processed).
method_gauge() is the companion to making_gauge(). It collects
effect-size functions for the base implementation and named variants,
used only when fn returns a non-class_stat_infer object.
method_gauge(default = NULL, ...)method_gauge(default = NULL, ...)
default |
A function with signature |
... |
Named functions, one per variant. Names must match variant
names registered in |
A method_gauge S7 object.
making_gauge(), auto_gauge(), class_stat_infer
method_predict() is the companion to making_predict(). It collects
predict functions for the base implementation and named variants, used
only when fn returns a non-class_stat_infer object.
method_predict(default = NULL, ...)method_predict(default = NULL, ...)
default |
A function with signature |
... |
Named functions, one per variant. Names must match variant
names registered in |
A method_predict S7 object.
making_predict(), auto_predict(), class_stat_infer
method_tidy() is the companion to making_tidy(). It collects tidy
functions for the base implementation and named variants, used only when
fn returns a non-class_stat_infer object.
method_tidy(default = NULL, ...)method_tidy(default = NULL, ...)
default |
A function with signature |
... |
Named functions, one per variant. Names must match variant
names registered in |
A method_tidy S7 object.
making_tidy(), auto_tidy(), class_stat_infer
MODEL_FN() is a developer-interface constructor for user-facing model
functions like LINEAR_REG(). It returns a function that routes to the
correct implementation based on the variable mapper <var_id> and method variant.
MODEL_FN(cls, defs, .name)MODEL_FN(cls, defs, .name)
cls |
A string naming the model class, e.g. |
defs |
A list of |
.name |
A string used as the model title in output. |
A function with signature function(.var_id, .data, ...).
HTEST_FN(), stat_define(), prepare_model(), via(), conclude()
A function for development use to extract the information in Variable Mappers.
model_processor(var_id, data = NULL, ...)model_processor(var_id, data = NULL, ...)
var_id |
The Variable Mappers to be extracted. |
data |
Optional. Only passed when a certain data structure (normally it's data frame) is required. |
... |
Passed through S7 method compatibility. |
Methods accept an optional data argument — a data frame, or NULL
to resolve variables from the calling environment.
A named list. The default method returns an empty list; each
registered method returns a list shaped for its var_id subclass (for
example, x_data/group_data for x_by(), or x/n for prop()).
%<-% registers a method_tidy() into the tidy registry. The
left-hand side must be a making_tidy() call.
lhs %<-% rhslhs %<-% rhs
lhs |
A |
rhs |
A |
NULL invisibly, called for its side effects.
making_tidy(T_TEST, x_by) %<-% method_tidy( default = function(.x, ...) { ... }, boot = function(.x, ...) { ... } )making_tidy(T_TEST, x_by) %<-% method_tidy( default = function(.x, ...) { ... }, boot = function(.x, ...) { ... } )
Mean of a variable, optionally conditioned on a subgroup
MU(x, given = NULL)MU(x, given = NULL)
x |
A bare variable name. |
given |
An optional filter predicate as a bare expression. |
A MU / param_obj S7 object.
MU(extra) MU(extra, group == "1")MU(extra) MU(extra, group == "1")
state_null() captures a hypothesis expression and attaches it to a
test_lazy object.
state_null(.x, ...)state_null(.x, ...)
.x |
A |
... |
Currently unused. |
The modified test_lazy object.
exprA hypothesis expression. It is passed after prepare_test(...) to supply
the hypothesis expression, e.g.
... |> prepare_test(T_TEST) |> state_null(expr = MU(x) == 0)
# Using binomial test as a simple example define_model(prop(45, 100)) |> prepare_test(P_TEST) |> state_null(2 * PI() == 0.25) |> conclude()# Using binomial test as a simple example define_model(prop(45, 100)) |> prepare_test(P_TEST) |> state_null(2 * PI() == 0.25) |> conclude()
on() creates an on Variable Mapper that describes one or more variables
to be tested independently. Expressions are captured unevaluated, similar to
how ggplot2::aes() captures aesthetics.
on(..., .block = NULL)on(..., .block = NULL)
... |
Bare variable names, tidyselect helpers (requires |
.block |
Optional. The blocking variable identifying experimental units.
Accepts a bare name, a tidyselect helper, or |
When multiple variables are supplied, the intended test is run once per
variable with no pairwise combinations formed — for that, use pairwise().
The optional .block argument identifies the experimental unit (e.g. a
subject ID column). When supplied, rows in the extracted data are aligned by
block before the test is run — this is required for blocked designs such as
the Friedman test where row position encodes block identity.
An on / var_id S7 object.
x_by(), rel(), pairwise(), prop()
# Single variable on(x) # Multiple variables — test on independently on(a, b, c) # Multiple variables — With a blocking factor on(pre, post, followup, .block = subject) # Tidyselect (requires data in define_model()) on(where(is.numeric))# Single variable on(x) # Multiple variables — test on independently on(a, b, c) # Multiple variables — With a blocking factor on(pre, post, followup, .block = subject) # Tidyselect (requires data in define_model()) on(where(is.numeric))
P_TEST() performs a one-sample proportion test using either an exact
binomial test or a normal approximation. If P_TEST is supplied within the lazy-loaded pipeline,
supply P_TEST as a function within i.e. prepare_test(.test = P_TEST) call.
P_TEST(.var_id = NULL, .data = NULL, ...)P_TEST(.var_id = NULL, .data = NULL, ...)
.var_id |
A registered variable mapper |
.data |
Unused. Accepted for pipeline consistency. |
... |
Additional arguments passed to the implementation. See the Arguments and Variants sections below. |
A cld_exec object, or a test_spec when .var_id = NULL.
The object stored in cld_exec@data is a class_p_test object.
The following arguments are passed via ... in P_TEST() or via():
.pNumeric. Hypothesized proportion under H, used directly
in stats::binom.test() / stats::prop.test(). Default 0.5. When a
hypothesis is stated via state_null() with a scaled claim like
c * PI() == k, .p is resolved to the solved value k / c, since
c * PI() == k and PI() == k / c are the same hypothesis (the
binomial likelihood is invariant under this linear reparameterization).
.altDirection: "two.sided", "greater", or "less".
Default "two.sided".
.ciConfidence level. Default 0.95.
.true_pOnly meaningful via state_null(). Carries the
hypothesis's scalar value as written (unsolved), purely for display
in true_p. Default NULL, in which case true_p falls back to
.p. Not intended to be set directly by users.
"prop"Normal approximation via stats::prop.test() without
continuity correction. Accepts the same .p, .alt, .ci arguments
as the default, except with correct addition to indicate whether Yates'
continuity correction should be applied or not.
Supports PI() via state_null():
define_model(prop(45, 100)) |>
prepare_test(P_TEST) |>
state_null(PI() == 0.5) |>
conclude()
Scaled claims are also supported, e.g. 2 * PI() == 0.3. The test itself
solves for PI() (.p = 0.15) and runs exactly via stats::binom.test()
or stats::prop.test() — no approximation is introduced by the scaling,
since testing c * PI() == k is mathematically identical to testing
PI() == k / c. true_p in the printed/tidied output instead shows the
scalar as written on the right-hand side of the claim (0.3, not the
solved 0.15), so the displayed hypothesis matches what was typed even
though the underlying test operates on the solved proportion.
prop(), class_p_test, PI(), state_null(), via(),
conclude()
P_TEST(prop(45, 100)) # piped syntax define_model(prop(45, 100)) |> prepare_test(P_TEST) |> conclude() # normal approximation define_model(prop(45, 100)) |> prepare_test(P_TEST) |> via("prop") |> conclude() # hypothesis claim define_model(prop(45, 100)) |> prepare_test(P_TEST) |> state_null(PI() == 0.3) |> conclude() # scaled hypothesis claim define_model(prop(45, 100)) |> prepare_test(P_TEST) |> state_null(2 * PI() == 0.3) |> conclude()P_TEST(prop(45, 100)) # piped syntax define_model(prop(45, 100)) |> prepare_test(P_TEST) |> conclude() # normal approximation define_model(prop(45, 100)) |> prepare_test(P_TEST) |> via("prop") |> conclude() # hypothesis claim define_model(prop(45, 100)) |> prepare_test(P_TEST) |> state_null(PI() == 0.3) |> conclude() # scaled hypothesis claim define_model(prop(45, 100)) |> prepare_test(P_TEST) |> state_null(2 * PI() == 0.3) |> conclude()
pairwise() creates a pairwise Variable Mapper from a set of variables,
producing all unique variable pairs. Use direction to control which
pairs are retained. Pairs are filtered by lexicographic (alphabetical)
ordering of variable names.
pairwise(..., direction = "lt")pairwise(..., direction = "lt")
... |
Bare variable names, tidyselect helpers (requires |
direction |
A string controlling which pairs are kept:
|
A pairwise / var_id S7 object.
pairwise(a, b, c) # Inline data pairwise(I(rnorm(30)), I(rnorm(30)), I(rnorm(30))) # Keep all ordered pairs pairwise(a, b, c, direction = "all")pairwise(a, b, c) # Inline data pairwise(I(rnorm(30)), I(rnorm(30)), I(rnorm(30))) # Keep all ordered pairs pairwise(a, b, c, direction = "all")
param_obj is the abstract base S7 class for all population parameter
objects, analogous to var_id(). Concrete subclasses (MU, PI,RHO)
inherit from it. The base class is a pure marker — each
subclass declares its own properties.
param_obj()param_obj()
An S7 abstract class generator. param_obj cannot be
instantiated directly, so calling it raises an error. It exists only as a
parent class for the concrete parameter classes (MU, PI, RHO).
Proportion of a variable, optionally conditioned on a subgroup
PI(x, given = NULL)PI(x, given = NULL)
x |
An empty or a bare variable name. |
given |
An optional filter predicate as a bare expression. |
A PI / param_obj S7 object.
PI() PI(success) PI(success, group == "treatment")PI() PI(success) PI(success, group == "treatment")
predict() estimates the response for new or existing rows from a
cld_exec object produced by conclude().
predict(object, new_data = NULL, ..., check_type = TRUE)predict(object, new_data = NULL, ..., check_type = TRUE)
object |
A |
new_data |
A data frame (or subclass, e.g. |
... |
Passed to the dispatched method. |
check_type |
Check whether the returned output is a data frame. If |
An object of class S7_external_generic of length 4.
A data frame (specifically a tibble) with .pred, truth
when a response is available, and .pred_lower/.pred_upper when
an interval was requested. Always inherits data.frame, regardless
of which method produced it.
Dispatches on object only, consistent with how stats::predict itself
works as a single-dispatch S3 generic. new_data's shape is validated
at the top of the method body rather than through a second S7 dispatch
argument — an S7 method can't reliably distinguish "argument omitted
entirely" from "argument explicitly NULL" when layered on top of a
legacy S3 generic, so validating inside the body is both simpler and
actually correct.
Two paths are tried in order:
Path 1: auto_predict() (preferred).
Called directly when cld_exec@data is a class_stat_infer subclass.
Path 2: making_predict() registry (escape hatch).
Used when a variant's fn intentionally returns a non-class_stat_infer
object.
conclude(), auto_predict(), making_predict()
prepare() attaches a spec function produced from STAT_CONSTRUCTOR() to a
<def_var> object and dispatches to prepare_test() or prepare_model()
depending on whether .fn returns a <test_spec> or a <model_spec>.
The result is a lazy pipeline object ready for optional recalibration
with via() before execution with conclude().
prepare(.x, .fn, ...)prepare(.x, .fn, ...)
.x |
A |
.fn |
A stat function built with |
... |
Additional arguments passed to the dispatched |
A <test_lazy> object if .fn returns a <test_spec>, or a
<model_lazy> object if .fn returns a <model_spec>.
prepare_test(), prepare_model(), define_model(), via(), conclude()
sleep |> define_model(x_by(extra, group)) |> prepare(T_TEST) |> conclude() mtcars |> define_model(mpg ~ .) |> prepare(LINEAR_REG) |> conclude()sleep |> define_model(x_by(extra, group)) |> prepare(T_TEST) |> conclude() mtcars |> define_model(mpg ~ .) |> prepare(LINEAR_REG) |> conclude()
prepare_model() attaches a model specification to a <def_var> object,
producing a <model_lazy> ready for optional recalibration with via()
before being executed with conclude().
prepare_model(.x, .model_fn, ...)prepare_model(.x, .model_fn, ...)
.x |
An S7 object extension yielded by, e.g. |
.model_fn |
A model function such as |
... |
Additional arguments passed to methods. |
A <model_lazy> S7 object.
prepare_test(), define_model(), via(), conclude()
mtcars |> define_model(rel(mpg, wt)) |> prepare_model(LINEAR_REG) |> conclude()mtcars |> define_model(rel(mpg, wt)) |> prepare_model(LINEAR_REG) |> conclude()
prepare_test() attaches a test specification to a <def_var> object,
producing a test_lazy ready for optional recalibration with via()
before being executed with conclude().
prepare_test(.x, .test, ...)prepare_test(.x, .test, ...)
.x |
An S7 object extension yielded by, e.g. |
.test |
A test function such as T_TEST that carries |
... |
Additional arguments passed to methods. |
A <test_lazy> S7 object.
define_model(), via(), conclude()
sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> conclude()sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> conclude()
prop() creates a prop Variable Mapper for proportion tests. Both arguments
are scalar constants, and this implies the arguments are expressions
that are not captured.
prop(x, n)prop(x, n)
x |
Number of successes. A non-negative integer scalar, |
n |
Total number of trials. A positive integer scalar. |
A prop / var_id S7 object.
prop(45, 100)prop(45, 100)
Call this from your package's .onUnload() to clean up entries registered
via add_stat_define(..., origin = "package").
purge_stat_defines(pkg)purge_stat_defines(pkg)
pkg |
A string. The package name, typically the |
NULL, invisibly.
# In your package's zzz.R: .onUnload = function(libpath) { statim::purge_stat_defines("yourpackage") }# In your package's zzz.R: .onUnload = function(libpath) { statim::purge_stat_defines("yourpackage") }
rel() creates a rel Variable Mapper that reads as "relationship between
x and resp". Expressions are captured unevaluated, similar to how
ggplot2::aes() captures aesthetics.
rel(x, resp)rel(x, resp)
x |
The predictor variable. Accepts a bare name, a |
resp |
The response variable. Same rules as |
A rel / var_id S7 object.
rel(speed, dist)rel(speed, dist)
Population correlation between two variables
RHO(x, y)RHO(x, y)
x |
A bare variable name. |
y |
A bare variable name. |
A RHO / param_obj S7 object.
RHO(speed, dist)RHO(speed, dist)
This function is a developer-interface function, a constructor for
user-facing test functions like HTEST_FN(). It returns a function with
a consistent signature that routes to the correct implementation based
on the variable mapper <var_id> and method variant.
STAT_CONSTRUCTOR(cls, defs, .name, spec_class)STAT_CONSTRUCTOR(cls, defs, .name, spec_class)
cls |
A string naming the test class, e.g. |
defs |
A list of |
.name |
A string used as the test title in output. |
spec_class |
Base class of the type of statistical inference. Must be an S7. |
A function with signature function(.var_id, .data, ...).
test_define(), prepare_test(), via(), conclude()
stat_define() declares a single implementation of a statistical procedure
for a given model type. Multiple stat_define objects are passed to
HTEST_FN() or MODEL_FN() via defs. This is the main extension point
for adding new tests or models.
stat_define(model_type = NULL, impl = NULL, compatible_params = list()) test_define(model_type = NULL, impl = NULL, compatible_params = list()) model_infer_define(model_type = NULL, impl = NULL, compatible_params = list())stat_define(model_type = NULL, impl = NULL, compatible_params = list()) test_define(model_type = NULL, impl = NULL, compatible_params = list()) model_infer_define(model_type = NULL, impl = NULL, compatible_params = list())
model_type |
A variable mapper |
impl |
An |
compatible_params |
A list of S7 param classes (e.g. |
A stat_define S7 object.
agendas(), baseline(), variant(), model_processor(),
HTEST_FN(), MODEL_FN()
T_TEST() performs a t-test for one-sample, two-sample, paired, pairwise, or
formula-based comparisons. If T_TEST is supplied within the lazy-loaded pipeline,
supply T_TEST as a function within i.e. prepare_test(.test = T_TEST) call.
T_TEST(.var_id = NULL, .data = NULL, ...)T_TEST(.var_id = NULL, .data = NULL, ...)
.var_id |
A variable mapper |
.data |
A data frame. Only used on the standalone path. |
... |
Additional arguments passed to the implementation. See the Arguments by variable mapper section for the full list per path. |
A cld_exec object (in conclude()), a stat_infer_spec object, or a
test_spec when .var_id = NULL. Depending on the implementation you wrote, it returns
any class. However, by default, some implementations use base {statim} S7 classes.
For instance:
ttest_x_by, by default, returns a class_ttest_two object
ttest_pairwise, by default, returns a class_ttest_pairwise object
<var_id>sEach variable mapper <var_id> routes to a separate implementation. See the linked pages
for full argument lists, variants, and result class details:
on(): one-sample t-test. See details from ttest-on.
x_by(): two-sample or paired t-test. See details from ttest-xby.
pairwise(): pairwise t-tests across variables. See details from ttest-pairwise.
<formula>: one-sample and/or two-sample t-test. See details from ttest-formula.
Welch, B. L. (1947). The generalization of "Student's" problem when several different population variances are involved. Biometrika, 34(1-2), 28-35. doi:10.1093/biomet/34.1-2.28
Satterthwaite, F. E. (1946). An approximate distribution of estimates of variance components. Biometrics Bulletin, 2(6), 110-114. doi:10.2307/3002019
Kutner, M. H., Nachtsheim, C. J., Neter, J., & Li, W. (2004). Applied Linear Statistical Models (5th ed.). McGraw-Hill/Irwin.
ttest-on, ttest-xby, ttest-pairwise, ttest-formula for per-implementation
details. class_ttest_two, class_ttest_pairwise for result class
slots. via(), state_null(), conclude(), auto_tidy().
# eager T_TEST(x_by(extra, group), sleep) # pipeline sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> conclude() # bootstrap sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> via("boot", n = 2000) |> conclude() # permutation sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> via("permute", n = 2000) |> conclude() # Contrast t-test # This uses `state_null()` in a higher degree # This performs Welch-Satterthwaite linear contrast test for t-test sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> state_null( 2 * MU(extra, group == "1") <= MU(extra, group == "2") ) |> # Try to obtain 90% of the confidence interval via("contrast", .ci = 0.9) |> conclude() # pairwise iris |> define_model(pairwise(Sepal.Length, Sepal.Width, Petal.Length)) |> prepare_test(T_TEST) |> conclude()# eager T_TEST(x_by(extra, group), sleep) # pipeline sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> conclude() # bootstrap sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> via("boot", n = 2000) |> conclude() # permutation sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> via("permute", n = 2000) |> conclude() # Contrast t-test # This uses `state_null()` in a higher degree # This performs Welch-Satterthwaite linear contrast test for t-test sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> state_null( 2 * MU(extra, group == "1") <= MU(extra, group == "2") ) |> # Try to obtain 90% of the confidence interval via("contrast", .ci = 0.9) |> conclude() # pairwise iris |> define_model(pairwise(Sepal.Length, Sepal.Width, Petal.Length)) |> prepare_test(T_TEST) |> conclude()
tidy() extracts a tibble of primary results from a cld_exec object
produced by conclude().
tidy(.x, ...)tidy(.x, ...)
.x |
A |
... |
Passed to the dispatched method. |
The statistical output in a tibble data frame format.
Two paths are tried in order:
Path 1: auto_tidy() (preferred).
When cld_exec@data is a class_stat_infer subclass, auto_tidy() is
called directly on it. You need no registry, and S7 automatically dispatches on the
particular output class, and variants that return the same class inherit the method
automatically via the parent chain.
Path 2: making_tidy() registry (escape hatch).
When cld_exec@data is not a class_stat_infer subclass, for example, when a variant
intentionally returns any data structure e.g. just a plain list, S3, S4, or R6 object
(check_sic_s7 = FALSE), tidy() falls back to the registry populated
by making_tidy(). If no entry exists there either, an informative error
is raised.
auto_tidy(), making_tidy(), method_tidy(), class_stat_infer
mtcars |> define_model(mpg ~ .) |> prepare_model(LINEAR_REG) |> conclude() |> tidy()mtcars |> define_model(mpg ~ .) |> prepare_model(LINEAR_REG) |> conclude() |> tidy()
var_id is the abstract parent class for all Variable Mapper objects in
{statim}. Variable Mappers emulate R's formula interface, as they capture
variable expressions without evaluating them, describing the structure
of a statistical model to be passed into a pipeline.
Concrete subclasses include x_by(), rel(), and pairwise(). You
cannot instantiate var_id directly; use one of its subclasses.
An S7 abstract class generator. var_id cannot be instantiated
directly, so calling it raises an error. It exists only as a parent class
for the concrete Variable Mapper subclasses (x_by(), rel(),
pairwise(), prop()).
x_by(), rel(), pairwise(), prop()
var_id_info() extracts a consistent metadata structure from a Variable Mapper
object. When processed is supplied, variable previews and count-based
metadata are included in the result.
var_id_info(.var_id, processed = NULL, ...)var_id_info(.var_id, processed = NULL, ...)
.var_id |
A Variable Mapper object from |
processed |
A named list returned by |
... |
Currently unused. |
A class_var_inform S7 object with fields:
var_idThe original Variable Mapper object.
model_typeDerived from the class name of var_id.
argsA formatted string summarising the model's arguments.
Defaults to "<?>" for unregistered subclasses.
other_infoA named list of model-type-specific metadata. Empty for unregistered subclasses.
varsA list of lists with name and preview fields.
Empty for unregistered subclasses or when processed is NULL.
# without processed — no vars, no counts var_id_info(x_by(extra, group)) # with processed — includes vars and counts dm = define_model(x_by(extra, group), sleep) var_id_info(dm@var_id, dm@processed)# without processed — no vars, no counts var_id_info(x_by(extra, group)) # with processed — includes vars and counts dm = define_model(x_by(extra, group), sleep) var_id_info(dm@var_id, dm@processed)
variant() declares a named alternative implementation reachable only via
via(). Never runs on the eager path.
variant(fn, print = NULL, claim_parser = NULL)variant(fn, print = NULL, claim_parser = NULL)
fn |
A function whose first argument must be
Try run this to explore the structure: Additional named arguments are user-supplied statistical parameters
(e.g. variant(
fn = function(.proc, n = 1000L, seed = NULL) {
x = .proc$x_data[[1]]
group_data = .proc$group_data
# ...
}
)
A variant whose # inherits `auto_tidy()` from `new_out` S7 class
variant(fn = function(.proc, ...) { new_out(...) })
# overrides auto_tidy() via subclass
variant(fn = function(.proc, ...) { new_out_boot(...) })
# intentionally plain
variant(fn = function(.proc, ...) { list(...) })
|
print |
A function with signature |
claim_parser |
A |
A variant S7 object.
baseline(), agendas(), via(), model_processor(),
map_claim(), class_stat_infer, auto_tidy()
via() switches a lazy pipeline to an alternative method variant and
merges user-supplied arguments with the variant's declared defaults.
Works for both test_lazy and model_lazy pipelines.
via(.x, .method, ...)via(.x, .method, ...)
.x |
A |
.method |
A string naming the method variant. Must match a named
|
... |
Named arguments forwarded to the variant. |
The modified lazy object with recalibrate_spec populated.
sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> via("boot", n = 2000) |> conclude() sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> via("permute", n = 999L) |> conclude()sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> via("boot", n = 2000) |> conclude() sleep |> define_model(x_by(extra, group)) |> prepare_test(T_TEST) |> via("permute", n = 999L) |> conclude()
write_models() evaluates named model expressions sequentially against
.data, so each name is available to subsequent expressions via
stats::update(). Accepts any valid variable mapper <var_id>: <formulas>, rel(),
x_by(), or any registered var_id type.
write_models(.data, ...)write_models(.data, ...)
.data |
A data frame. |
... |
Named model expressions. Each must evaluate to a formula or
a |
Sits between a data frame and prepare_model() or prepare_test()
in the pipeline.
An expanded_model object.
prepare_model(), prepare_test(), anova(), conclude(),
display()
# explicit formulas LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75, f4 = sr ~ pop15 + pop75 + dpi, f5 = sr ~ pop15 + pop75 + dpi + ddpi ) |> prepare_model(LINEAR_REG) |> anova() # update() chain (formulas only) LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = update(f1, ~. + pop15), f3 = update(f2, ~. + pop75), f4 = update(f3, ~. + dpi), f5 = update(f4, ~. + ddpi) ) |> prepare_model(LINEAR_REG) |> anova() # conclude() -> returns a multi_exec LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75 ) |> prepare_model(LINEAR_REG) |> conclude() ## Not run: # display() -> show up to n models in full LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75, f4 = sr ~ pop15 + pop75 + dpi, f5 = sr ~ pop15 + pop75 + dpi + ddpi ) |> prepare_model(LINEAR_REG) |> conclude() |> display(5) ## End(Not run) # via rel() mtcars |> define_model(rel(wt, mpg)) |> prepare_model(LINEAR_REG) |> anova() mtcars |> write_models( m1 = rel(wt, mpg), m2 = rel(hp, mpg) ) |> prepare_model(LINEAR_REG) |> anova() # mixed var_id types in a single write_models() call suppressWarnings({ mtcars |> write_models( null = mpg ~ 1, m1 = rel(wt, mpg), m2 = rel(hp, mpg) ) |> prepare_model(LINEAR_REG) |> conclude() }) # via prepare_test() mtcars |> write_models( by_am = x_by(mpg, am), by_vs = x_by(mpg, vs) ) |> prepare_test(T_TEST) |> conclude()# explicit formulas LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75, f4 = sr ~ pop15 + pop75 + dpi, f5 = sr ~ pop15 + pop75 + dpi + ddpi ) |> prepare_model(LINEAR_REG) |> anova() # update() chain (formulas only) LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = update(f1, ~. + pop15), f3 = update(f2, ~. + pop75), f4 = update(f3, ~. + dpi), f5 = update(f4, ~. + ddpi) ) |> prepare_model(LINEAR_REG) |> anova() # conclude() -> returns a multi_exec LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75 ) |> prepare_model(LINEAR_REG) |> conclude() ## Not run: # display() -> show up to n models in full LifeCycleSavings |> write_models( f1 = sr ~ 1, f2 = sr ~ pop15, f3 = sr ~ pop15 + pop75, f4 = sr ~ pop15 + pop75 + dpi, f5 = sr ~ pop15 + pop75 + dpi + ddpi ) |> prepare_model(LINEAR_REG) |> conclude() |> display(5) ## End(Not run) # via rel() mtcars |> define_model(rel(wt, mpg)) |> prepare_model(LINEAR_REG) |> anova() mtcars |> write_models( m1 = rel(wt, mpg), m2 = rel(hp, mpg) ) |> prepare_model(LINEAR_REG) |> anova() # mixed var_id types in a single write_models() call suppressWarnings({ mtcars |> write_models( null = mpg ~ 1, m1 = rel(wt, mpg), m2 = rel(hp, mpg) ) |> prepare_model(LINEAR_REG) |> conclude() }) # via prepare_test() mtcars |> write_models( by_am = x_by(mpg, am), by_vs = x_by(mpg, vs) ) |> prepare_test(T_TEST) |> conclude()
x_by() (and its infix alias %by%) creates an x_by Variable Mapper that
reads as "compare x by group". Expressions are captured unevaluated,
similar to how ggplot2::aes() captures aesthetics.
x_by(x, group) x %by% groupx_by(x, group) x %by% group
x |
The response variable. Accepts a bare name, a |
group |
The grouping variable. Same rules as |
An x_by / var_id S7 object.
# Bare names — resolved later from the data or environment x_by(extra, group) # Infix alias: identical to x_by(extra, group) extra %by% group # Inline data via I() x_by(I(rnorm(30)), I(rep(c("a", "b"), each = 15))) # Named inline data x_by(I(score = rnorm(30)), I(grp = rep(c("a", "b"), each = 15)))# Bare names — resolved later from the data or environment x_by(extra, group) # Infix alias: identical to x_by(extra, group) extra %by% group # Inline data via I() x_by(I(rnorm(30)), I(rep(c("a", "b"), each = 15))) # Named inline data x_by(I(score = rnorm(30)), I(grp = rep(c("a", "b"), each = 15)))