R/interface_to_interface.R
matrix_to_formula.RdWraps a model function that expects a numeric matrix X and a response
vector y (like glmnet::glmnet) so it can be called with the
familiar formula + data interface. The formula is expanded via
model.matrix, which handles factor dummy-coding,
interactions, and inline transformations automatically.
matrix_to_formula(
fit_func,
predict_func = function(model, newX, ...) stats::predict(model, newdata = newX, ...)
)A model-fitting function whose first two positional
arguments are x (numeric matrix) and y (response vector),
e.g. glmnet::glmnet.
A prediction function with signature
function(model, newX, ...) where newX is a numeric matrix.
Defaults to a thin wrapper around stats::predict that passes
newdata as newx.
A named list with two elements:
fit(formula, data, ...)Fits the model. The formula is
expanded with model.matrix; the intercept column is dropped
before passing to fit_func (add it back via ... if your
model needs it). Extra arguments are forwarded to fit_func.
predict(model, newdata, ...)Generates predictions.
newdata is expanded with the same model.matrix terms
captured at fit time. Extra arguments are forwarded to
predict_func.
if (FALSE) { # \dontrun{
glmnet_formula <- matrix_to_formula(
fit_func = glmnet::glmnet,
predict_func = function(model, newX, ...) {
glmnet::predict.glmnet(model, newx = newX, s = 0.01, ...)
}
)
model <- glmnet_formula$fit(mpg ~ wt + hp + factor(cyl), data = mtcars)
glmnet_formula$predict(model, newdata = mtcars[1:5, ])
} # }