Wraps a model function that expects formula + data so it can be called with a plain X (data.frame or matrix) and y (vector). Factors in X are preserved; special column names are safely backtick-quoted in the generated formula so they survive the formula parser.

formula_to_matrix(fit_func, predict_func = stats::predict)

Arguments

fit_func

A model-fitting function whose first two arguments are formula and data (e.g. lm, glm).

predict_func

A prediction function with signature function(model, newdata, ...). Defaults to stats::predict.

Value

A named list with two elements:

fit(X, y, weights, ...)

Fits the model. X is a data.frame (or coercible matrix), y is the response vector. Extra arguments are forwarded to fit_func.

predict(model, newdata, ...)

Generates predictions. newdata must have the same columns as the X used in fit. Extra arguments are forwarded to predict_func.

Examples

lm_matrix <- formula_to_matrix(lm)
X <- data.frame(wt = mtcars$wt, hp = mtcars$hp, cyl = factor(mtcars$cyl))
y <- mtcars$mpg
model <- lm_matrix$fit(X, y)
lm_matrix$predict(model, X[1:5, ])
#>        1        2        3        4        5 
#> 21.60851 20.79725 26.31500 19.71558 17.67011