
Deterministic one-hot encoding of categorical model features from fixed level lists
Source:R/categorical_encoding.R
categorical_encoding.Rdmodel.matrix() / get_dummies(drop_first = TRUE) derive their columns from the levels present in the data, so the
same model sees different columns at a site that lacks a level. A model release should ship the level list of every
categorical feature; these functions always produce the same columns in the same order, named <feature>_<level>
(as pandas get_dummies does). Missing values encode as all zeros, which equals the reference level, so give
"missing" its own level when it matters (the SDI / RUCA labels do).
Usage
encoded_column_names(levels)
encode_categoricals(df, levels, unknown = c("error", "zero"), keep = FALSE)Arguments
- levels
Named list; each element is a character vector of levels, or a list with
levelsand an optionalreference(the level that gets no column;NULLkeeps every level).- df
A data frame.
- unknown
"error"(default) or"zero": what to do with a value outside the level list.- keep
Keep the original string columns as well.