R: Convert Strings to Factors

step_string2factor {recipes} | R Documentation

## Convert Strings to Factors

### Description

`step_string2factor` will convert one or more character vectors to factors (ordered or unordered).

### Usage

    step_string2factor(recipe, ..., role = NA, trained = FALSE, levels = NULL,
      ordered = FALSE, skip = FALSE)

    ## S3 method for class 'step_string2factor'
    tidy(x, ...)

### Arguments

`recipe` | A recipe object. The step will be added to the sequence of operations for this recipe.
`...` | One or more selector functions to choose which variables will converted to factors. See `selections()` for more details. For the `tidy` method, these are not currently used.
`role` | Not used by this step since no new variables are created.
`trained` | A logical to indicate if the quantities for preprocessing have been estimated.
`levels` | An options specification of the levels to be used for the new factor. If left `NULL`, the sorted unique values present when `bake` is called will be used.
`ordered` | A single logical value; should the factor(s) be ordered?
`skip` | A logical. Should the step be skipped when the recipe is baked by `bake.recipe()`? While all operations are baked when `prep.recipe()` is run, some operations may not be able to be conducted on new data (e.g. processing the outcome variable(s)). Care should be taken when using `skip = TRUE` as it may affect the computations for subsequent operations
`x` | A `step_string2factor` object.

### Details

If `levels` is given, `step_string2factor` will convert all factors to have the same levels. Also, note that `prep` has an option `stringsAsFactors` that defaults to `TRUE`. This should be changed so that raw character data will be applied to `step_string2factor`.

### Value

An updated version of `recipe` with the new step added to the sequence of existing steps (if any). For the `tidy` method, a tibble with columns `terms` (the selectors or variables selected) and `ordered`.

### See Also

`step_factor2string()` `step_dummy()` `step_other()` `step_novel()`

### Examples

    data(okc)

    rec <- recipe(~ diet + location, data = okc)

    make_factor <- rec %>%
      step_string2factor(diet)
    make_factor <- prep(make_factor,
                        training = okc,
                        stringsAsFactors = FALSE,
                        retain = TRUE)

    # note that `diet` is a factor
    juice(make_factor) %>% head
    okc %>% head
    tidy(make_factor, number = 1)

[Package recipes version 0.1.2 Index]