Construct a model matrix while optionally retaining all levels of factor variables (i.e., do not drop a reference level). This can be useful for LASSO-style models or other workflows where a fixed reference level is undesirable. Optionally returns a sparse model matrix.
Arguments
- formula
A model formula passed to
model.matrix.- df
A data.frame providing the variables in
formula.- sparse
Logical; if TRUE, return a sparse model matrix via
Matrix::sparse.model.matrix.- all_levels
Logical; if TRUE, keep all levels of all factor variables (non-full-rank design). If FALSE, use default treatment contrasts which drop one level (full rank).
Details
This helper mirrors the behavior of a legacy script that prefixed factor
and character values to produce stable column names and then supplied
explicit contrast matrices to model.matrix/sparse.model.matrix.
Examples
df <- data.frame(y = rnorm(5), f = factor(c("a","b","a","c","b")), x = 1:5)
mm1 <- modmat(y ~ f + x, df, sparse = FALSE, all_levels = TRUE)
mm2 <- modmat(y ~ f + x, df, sparse = TRUE, all_levels = FALSE)