The hardhat package provides infrastructure for building modeling packages with consistent interfaces. It standardizes preprocessing via
(training) and
(prediction), handling formula, XY, and recipe inputs uniformly.
Create objects of your model class. Name:
.
r
new_simple_lm <- function(coefs, coef_names, blueprint) {
if (!is.numeric(coefs)) {
stop("`coefs` should be a numeric vector.", call. = FALSE)
}
if (!is.character(coef_names)) {
stop("`coef_names` should be a character vector.", call. = FALSE)
}
new_model(
coefs = coefs,
coef_names = coef_names,
blueprint = blueprint,
class = "simple_lm"
)
}
Core algorithm. Name:
. Returns named list of model elements.
Connects user-facing methods to implementation. Converts
output to implementation format.
Generic with methods for each interface. Each method calls
then the bridge.
r
simple_lm <- function(x, ...) {
UseMethod("simple_lm")
}
simple_lm.default <- function(x, ...) {
stop("`simple_lm()` is not defined for a '", class(x)[1], "'.", call. = FALSE)
}
simple_lm.data.frame <- function(x, y, intercept = TRUE, ...) {
blueprint <- default_xy_blueprint(intercept = intercept)
processed <- mold(x, y, blueprint = blueprint)
simple_lm_bridge(processed)
}
simple_lm.matrix <- function(x, y, intercept = TRUE, ...) {
blueprint <- default_xy_blueprint(intercept = intercept)
processed <- mold(x, y, blueprint = blueprint)
simple_lm_bridge(processed)
}
simple_lm.formula <- function(formula, data, intercept = TRUE, ...) {
blueprint <- default_formula_blueprint(intercept = intercept)
processed <- mold(formula, data, blueprint = blueprint)
simple_lm_bridge(processed)
}
simple_lm.recipe <- function(x, data, intercept = TRUE, ...) {
blueprint <- default_recipe_blueprint(intercept = intercept)
processed <- mold(x, data, blueprint = blueprint)
simple_lm_bridge(processed)
}
One function per prediction type. Use
for standardized output.
Converts
output and switches on type.
Call
with blueprint, then bridge, then validate.
r
predict.simple_lm <- function(object, new_data, type = "numeric", ...) {
processed <- forge(new_data, object$blueprint)
out <- predict_simple_lm_bridge(type, object, processed$predictors)
validate_prediction_size(out, new_data)
out
}