--- 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, focusing on the main function of `anticlust`: `anticlustering()`. Historically, the first option we had to deal with categorical variables was the `categories` argument (Papenberg & Klau, 2021). 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 its usage: ```{r} data(penguins) # First exclude cases with missing values df <- na.omit(palmerpenguins::penguins) head(df) nrow(df) ``` In the data set, each row represents a penguin, and the data set has four numeric variables (bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g) 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_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g")] 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`. ## Blocking As of version 0.8.13, we have another option of incorporating categorical variables with `anticlustering()`: blocking. It is pretty similar to using the `categories` argument: ```{r} groups1 <- anticlustering( numeric_vars, K = 3, categories = df$sex, standardize = TRUE, objective = "kplus", method = "local-maximum" ) groups2 <- anticlustering( numeric_vars, K = 3, blocks = df$sex, standardize = TRUE, objective = "kplus", method = "local-maximum" ) table(df$sex, groups1) table(df$sex, groups2) ``` There is one difference: With blocking, we also attempt to balance the numeric variables within each level of the blocking variable across groups; with the categories argument, we only attempt to achieve overall balance. As we can see: ```{r} knitr::kable(mean_sd_tab(numeric_vars[df$sex == "female", ], groups1[df$sex == "female"]), row.names = TRUE) # categories argument knitr::kable(mean_sd_tab(numeric_vars[df$sex == "female", ], groups2[df$sex == "female"]), row.names = TRUE) # blocks argument knitr::kable(mean_sd_tab(numeric_vars[df$sex == "male", ], groups1[df$sex == "male"]), row.names = TRUE) # categories argument knitr::kable(mean_sd_tab(numeric_vars[df$sex == "male", ], groups2[df$sex == "male"]), row.names = TRUE) # blocks argument ``` Within each species, there is increased similarity between groups when using the blocks argument. Note that this is currently *only* achieved with the blocks argument; it is also not achieved when using the categorical variables as factors as described above.[^interaction] [^interaction]: It should be possible to manually construct the input matrix `x` in such a way that it includes an interaction term for the blocking variable and the other variables of interest. In this case, we should also obtain balance within each level of the blocking variable. We are already doing the same thing in `categories_to_binary()` -- however, just with categorical variables -- when using `use_combinations`. With `model.matrix()`, advanced users may be able to construct interaction variables for categorical and numeric variables; future versions of `anticlust` may offer convenience support for this option. ## References Papenberg, M., & Klau, G. W. (2021). Using anticlustering to partition data sets into equivalent parts. *Psychological Methods, 26*(2), 161--174. https://doi.org/10.1037/met0000301