--- title: "Using categorical variables with anticlustering" output: rmarkdown::html_vignette author: Martin Papenberg vignette: > %\VignetteIndexEntry{Using categorical variables with anticlustering} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) set.seed(123) ``` ```{r setup} library(anticlust) ``` In this vignette I explore some ways to incorporate categorical variables with anticlustering. The main function of `anticlust` is `anticlustering()`, and it has an argument `categories`. It can be used easily enough: We just pass the numeric variables as first argument (`x`) and our categorical variable(s) to `categories`. I will use the penguin data set to illustrate the usage: ```{r} data(penguins) # First exclude cases with missing values df <- na.omit(penguins) head(df) nrow(df) ``` In the data set, each row represents a penguin, and the data set has four numeric variables (bill_len, bill_dep, flipper_len, body_mass) and several categorical variables (species, island, sex) as descriptions of the penguins. Let's call `anticlustering()` to divide the `r nrow(df)` penguins into 3 groups. We use the four the numeric variables as first argument (i.e., the anticlustering objective is computed on the basis of the numeric variables), and the penguins' sex as categorical variable: ```{r} numeric_vars <- df[, c("bill_len", "bill_dep", "flipper_len", "body_mass")] groups <- anticlustering( numeric_vars, K = 3, categories = df$sex ) ``` Let's check out how well our categorical variables are balanced: ```{r} table(groups, df$sex) ``` A perfect split! Similarly, we could use the species as categorical variable: ```{r} groups <- anticlustering( numeric_vars, K = 3, categories = df$species ) table(groups, df$species) ``` As good as it could be! Now, let's use both categorical variables at the same time: ```{r} groups <- anticlustering( numeric_vars, K = 3, categories = df[, c("species", "sex")] ) table(groups, df$sex) table(groups, df$species) ``` The results for the sex variable are worse than previously when we only considered one variable at a time. This is because when using multiple variables with the `categories` argument, all columns are "merged" into a single column, and each combination of sex / species is treated as a separate category. Some information on the original variables is lost, and the results may become less optimal---while being still pretty okay here. Alas, using only the `categories` argument, we cannot improve this balancing even if a better split with regard to both categorical variables would be possible. ## Categorical variables as numeric variables A second possibility to incorporate categorical variables is to treat them as numeric variables and use them as part of the first argument `x`, which is used to compute the anticlustering objective (e.g., the diversity or variance). This approach can lead to better results when multiple categorical variables are available, and / or if the group sizes are unequal. Since version 0.8.12, we can use categorical variables as part of the first argument when they are defined as factors. Before that, we manually had to convert categorical variables into a binary representation via `categories_to_binary()`. Manual conversion can still be useful, as shown further below. In the penguin data sets, all variables are already correctly coded, i.e., categorical variables are defined as factors. So I generate a data frame that includes all features -- numeric and categorical features -- and use it as input for anticlustering. ```{r} all_features <- data.frame(numeric_vars, df[, c("species", "sex")]) ``` ```{r} groups <- anticlustering( all_features, K = 3, method = "local-maximum", standardize = TRUE ) table(groups, df$sex) table(groups, df$species) ``` The results are quite convincing. In particular, the penguins' sex is better balanced than previously when we used the argument `categories`. If we have multiple categorical variables and / or unequal-sized groups, it may be useful to try out using categorical variables as factors, instead of using the `categories` argument. If we also wish to ensure that the categorical variables *in their combination* are balanced between groups, we must do some manual data preparation. For anticlustering, categorical variables are converted into a binary representation via "one hot" encoding. The `anticlust` package has the convenience function `categories_to_binary()`. for this purpose.[^modelmatrix] This is done internally via `anticlustering()` when using categorical variables as part of the data input (as factors). In that case, however, combinations of categorical variables are not considered. To consider combinations, we can manually create our data set with binary categorical variables, setting the optional argument `use_combinations` of `categories_to_binary()` to `TRUE`. First, let's see how we would manually encode categorical variables without considering their combinations. We will use collection year (2007, 2008, 2009) and species as categorical variables: [^modelmatrix]: Internally, `categories_to_binary()` is wrapper around the base `R` function `model.matrix()`. ```{r} binary_categories <- categories_to_binary(df[, c("species", "year")], use_combinations = FALSE) data_input <- data.frame(binary_categories, numeric_vars) groups <- anticlustering( data_input, K = 3, method = "local-maximum", standardize = TRUE ) table(groups, df$year, df$species) ``` When setting `use_combinations = TRUE`, we will also balance the proportions of species collected in each year across groups, which was not explicitly done before: ```{r} binary_categories <- categories_to_binary(df[, c("species", "year")], use_combinations = TRUE) data_input <- data.frame(binary_categories, numeric_vars) groups <- anticlustering( data_input, K = 3, method = "local-maximum", standardize = TRUE ) table(groups, df$year, df$species) ``` Now, the year of data collection is perfectly balance across groups for each of the three species, which is not accomplished when setting `use_combinations = FALSE` or when using the categories as factors, which internally sets `use_combinations = FALSE`.