Encode factor / categorical covariates into a numeric matrix
Source:R/utils-encoding.R
rr_encode_factors.RdExpands the factor / character columns of a data frame into a numeric design
matrix using one of several encodings, and returns both the encoded matrix
and a reusable recipe (encoding_info) that rr_encode_apply() replays on
new data. Numeric columns pass through unchanged in their original position.
Usage
rr_encode_factors(
x,
mode = c("onehot", "means", "integer", "auto", "manual"),
spec = NULL,
folds = NULL,
auto_onehot_max = 10L,
min_level_n = 1L,
prefix = "encode"
)Arguments
- x
A data frame (or object coercible to one). Numeric columns pass through; factor / character columns are encoded. Logical columns are treated as numeric (0/1).
- mode
Encoding applied to every factor column:
"onehot"– treatment dummies, identical tomodel.matrix(~ ., x)[, -1]."means"– sufficient-representation means encoding: each level is replaced by the within-level means of the other numeric covariates, \(E[X_{other} \mid G = g]\). Leakage-free with respect to the response, and optionally computed out-of-fold viafolds."integer"– ordinal codes1..L, one column per factor."auto"– per-factor rule: one-hot when the level count is<=auto_onehot_max, else means when numeric covariates exist, else integer."manual"– interactive per-factor menu; errors in a non-interactive session (passspecinstead). After the prompts, a pasteablespec=code block reproducing the choices is printed to the console for non-interactive replay.
- spec
Optional named list of per-column modes (
"onehot"/"means"/"integer") overridingmodefor those columns. The deterministic, non-interactive alternative tomode = "manual".- folds
Optional fold ids (length
nrow(x)) for out-of-fold means encoding: each row's encoded value is computed from the complementary folds only, so a row never informs its own encoding. Ignored by non-means modes.- auto_onehot_max
Level-count threshold for
mode = "auto"(default 10).- min_level_n
Levels with fewer than this many rows fall back to the grand mean in means encoding (default 1).
- prefix
Label used in error / warning messages.
Value
A list with x (the encoded numeric matrix) and encoding_info (the
recipe consumed by rr_encode_apply()).
Examples
df <- data.frame(z = rnorm(20),
g = factor(sample(c("a", "b", "c"), 20, TRUE)))
enc <- rr_encode_factors(df, mode = "onehot")
head(enc$x)
#> z gb gc
#> 1 0.870005525 1 0
#> 2 1.656003734 0 1
#> 3 -0.006368929 0 1
#> 4 0.470489453 0 0
#> 5 0.278218649 0 1
#> 6 -0.977902941 0 0
m <- rr_encode_factors(df, mode = "means")
head(m$x)
#> z g_mean_z
#> 1 0.870005525 1.0980855
#> 2 1.656003734 0.3883175
#> 3 -0.006368929 0.3883175
#> 4 0.470489453 0.0735230
#> 5 0.278218649 0.3883175
#> 6 -0.977902941 0.0735230