step_dummy()
will create a set of binary dummy
variables from a factor variable. For example, if an unordered
factor column in the data set has levels of "red", "green",
"blue", the dummy variable bake will create two additional
columns of 0/1 data for two of those three values (and remove
the original column). For ordered factors, polynomial contrasts
are used to encode the numeric values.
By default, the excluded dummy variable (i.e. the reference
cell) will correspond to the first level of the unordered
factor being converted.
The function allows for non-standard naming of the resulting
variables. For an unordered factor named x
, with levels "a"
and "b"
, the default naming convention would be to create a
new variable called x_b
. Note that if the factor levels are
not valid variable names (e.g. "some text with spaces"), it will
be changed by base::make.names()
to be valid (see the example
below). The naming format can be changed using the naming
argument and the function dummy_names()
is the default. This
function will also change the names of ordinal dummy variables.
Instead of values such as ".L
", ".Q
", or "^4
", ordinal
dummy variables are given simple integer suffixes such as
"_1
", "_2
", etc.
To change the type of contrast being used, change the global
contrast option via options
.
When the factor being converted has a missing value, all of the
corresponding dummy variables are also missing. See step_unknown()
for
a solution.
When data to be processed contains novel levels (i.e., not
contained in the training set), a missing value is assigned to
the results. See step_other()
for an alternative.
If no columns are selected (perhaps due to an earlier step_zv()
),
bake()
will return the data as-is (e.g. with no dummy variables).
Note that, by default, the new dummy variable column names obey the naming
rules for columns. If there are levels such as "0", dummy_names()
will put
a leading "X" in front of the level (since it uses make.names()
). This can
be changed by passing in a different function to the naming
argument for
this step.
The package vignette for dummy variables
and interactions has more information.