Skip to contents

model.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 levels and an optional reference (the level that gets no column; NULL keeps 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.

Value

encoded_column_names(): the dummy column names. encode_categoricals(): df with each listed column replaced by 0/1 numeric dummies.