Convert all categorical variables into dummy/indicator variables
Source:R/factor.R
fct_data_dummify.RdTakes a data frame and separates all columns containing categorical variables
into dummy variables (one column per category). Unlike
stats::model.matrix(), does not exclude any categories from being converted
into columns, and retains missing values. If you need more control over your
dummy creation, we refer you to recipes::step_dummy().
Arguments
- data
A data frame containing the factors to be converted to dummies.
- dummify_characters
Logical; Should
charactervariables be converted to factors and dummified? Defaults toTRUE.- max_levels
Integer; The maximum number of levels that a categorical variable can have in order to be converted to dummies. This is to prevent converting variables such as respondent IDs or open-ended responses to dummy variables. Defaults to 52, which is slightly more than the number of U.S. states plus Washington, D.C.
- sep
Character; A string that will go in between the original variable name and the corresponding factor level in the output, e.g. VARIABLE_Category. Defaults to
"_".
Value
A copy of the original data frame where all factor variables have been replaced with dummies. Formatted as a tibble.
Examples
library(dplyr)
data <- HairEyeColor |> as_tibble() |> mutate(Eye = as.factor(Eye))
# Notice how all character and factor columns were dummified
fct_data_dummify(data)
#> # A tibble: 32 × 11
#> Hair_Black Hair_Blond Hair_Brown Hair_Red Eye_Blue Eye_Brown Eye_Green
#> <int> <int> <int> <int> <int> <int> <int>
#> 1 1 0 0 0 0 1 0
#> 2 0 0 1 0 0 1 0
#> 3 0 0 0 1 0 1 0
#> 4 0 1 0 0 0 1 0
#> 5 1 0 0 0 1 0 0
#> 6 0 0 1 0 1 0 0
#> 7 0 0 0 1 1 0 0
#> 8 0 1 0 0 1 0 0
#> 9 1 0 0 0 0 0 0
#> 10 0 0 1 0 0 0 0
#> # ℹ 22 more rows
#> # ℹ 4 more variables: Eye_Hazel <int>, Sex_Female <int>, Sex_Male <int>,
#> # n <dbl>
# Notice how only factor columns were dummified
fct_data_dummify(data, dummify_characters = FALSE)
#> # A tibble: 32 × 7
#> Hair Eye_Blue Eye_Brown Eye_Green Eye_Hazel Sex n
#> <chr> <int> <int> <int> <int> <chr> <dbl>
#> 1 Black 0 1 0 0 Male 32
#> 2 Brown 0 1 0 0 Male 53
#> 3 Red 0 1 0 0 Male 10
#> 4 Blond 0 1 0 0 Male 3
#> 5 Black 1 0 0 0 Male 11
#> 6 Brown 1 0 0 0 Male 50
#> 7 Red 1 0 0 0 Male 10
#> 8 Blond 1 0 0 0 Male 30
#> 9 Black 0 0 0 1 Male 10
#> 10 Brown 0 0 0 1 Male 25
#> # ℹ 22 more rows
# In this example, we want to limit dummification to columns with max 2 levels
fct_data_dummify(data, max_levels = 2)
#> # A tibble: 32 × 5
#> Hair Eye Sex_Female Sex_Male n
#> <fct> <fct> <int> <int> <dbl>
#> 1 Black Brown 0 1 32
#> 2 Brown Brown 0 1 53
#> 3 Red Brown 0 1 10
#> 4 Blond Brown 0 1 3
#> 5 Black Blue 0 1 11
#> 6 Brown Blue 0 1 50
#> 7 Red Blue 0 1 10
#> 8 Blond Blue 0 1 30
#> 9 Black Hazel 0 1 10
#> 10 Brown Hazel 0 1 25
#> # ℹ 22 more rows