recipes can assign one or more roles to each column in the data. The roles are not restricted to a predefined set; they can be anything. For most conventional situations, they are typically “predictor” and/or “outcome”. Additional roles enable targeted step operations on specific variables or groups of variables.

The Formula Method

When a recipe is created using the formula interface, this defines the roles for all columns of the data set. summary() can be used to view a tibble containing information regarding the roles.

These roles can be updated despite this initial assignment. update_role() can modify a single existing role:

When you want to get rid of a role for a column, use remove_role().

It represents the lack of a role as NA, which means that the variable is used in the recipe, but does not yet have a declared role. Setting the role manually to NA is not allowed:

recipe(HHV ~ ., data = biomass) %>% 
  update_role(sample, new_role = NA_character_)
#> Error: `new_role` must not be `NA`.

When there are cases when a column will be used in more than one context, add_role() can create additional roles:

If a variable has multiple existing roles and you want to update one of them, the additional old_role argument to update_role() must be used to resolve any ambiguity.

Additional variable roles allow you to use has_role() in combination with other selection methods (see ?selections) to target specific variables in subsequent processing steps. For example, in the following recipe, by adding the role "nocenter" to the HHV predictor, you can use -has_role("nocenter") to exclude HHV when centering all_predictors().

Role Inheritance

All recipes steps have a role argument that lets you set the role of new columns generated by the step. When a recipe modifies a column in-place, the role is never modified. For example, ?step_center has the documentation:

role: Not used by this step since no new variables are created

In other cases, the roles are defaulted to a relevant value based the context. For example, ?step_dummy has

role: For model terms created by this step, what analysis role should they be assigned?. By default, the function assumes that the binary dummy variable columns created by the original variables will be used as predictors in a model.

So, by default, they are predictors but don’t have to be:

recipe( ~ ., data = iris) %>% 
  step_dummy(Species) %>% 
  prep() %>% 
  juice(all_predictors()) %>% 
  dplyr::select(starts_with("Species")) %>% 
  names()
#> [1] "Species_versicolor" "Species_virginica"

# or something else
recipe( ~ ., data = iris) %>% 
  step_dummy(Species, role = "trousers") %>% 
  prep() %>% 
  juice(has_role("trousers")) %>% 
  names()
#> [1] "Species_versicolor" "Species_virginica"