R/ordinal_to_binary.R
ordinal_to_binary.Rd
convert a column of categorical covariates into a number of columns with a binary flag for each category
ordinal_to_binary_(df, col_name, prefix = NULL, overwrite = FALSE)
library(dplyr)
df <- tibble(OCC = c(1, 1, 2, 3))
df %>% ordinal_to_binary_("OCC")
#> OCC OCC1 OCC2 OCC3
#> 1 1 1 0 0
#> 2 1 1 0 0
#> 3 2 0 1 0
#> 4 3 0 0 1
df %>% ordinal_to_binary_("OCC", prefix = "OCCASION")
#> OCC OCCASION1 OCCASION2 OCCASION3
#> 1 1 1 0 0
#> 2 1 1 0 0
#> 3 2 0 1 0
#> 4 3 0 0 1
df2 <- tibble(OCC = c(1, 1, 2, 3), OCC1 = 999)
df2 %>% ordinal_to_binary_("OCC")
#> Warning: detected existing columns with same name sequence,
#> prepending "_" to all generated columns.
#> OCC OCC1 _OCC1 _OCC2 _OCC3
#> 1 1 999 1 0 0
#> 2 1 999 1 0 0
#> 3 2 999 0 1 0
#> 4 3 999 0 0 1
df2 %>% ordinal_to_binary_("OCC", overwrite = TRUE)
#> OCC OCC1 OCC2 OCC3
#> 1 1 1 0 0
#> 2 1 1 0 0
#> 3 2 0 1 0
#> 4 3 0 0 1