encode_categorical: Encode categorical variables

View source: R/encode_categorical.R

encode_categoricalR Documentation

Encode categorical variables

Description

Converts factor or character columns into numeric representations using label encoding, frequency encoding, or one-hot encoding. One-hot encoding creates binary indicator columns for each category.

Usage

encode_categorical(data, cols = NULL, method = "label",
                   group = NULL, prefix = "enc_", verbose = FALSE)

Arguments

data

A data frame containing categorical variables.

cols

The column indices or names of selected categorical variables. If NULL (default), all factor and character columns are selected automatically. An error is raised if any explicitly selected column is not categorical.

method

Encoding method. One of "label" (integer labels), "frequency" (frequency of each category), or "onehot" (binary indicator columns).

group

Optional grouping column for grouped frequency encoding.

prefix

Prefix for one-hot encoded column names (used only when method = "onehot").

verbose

Logical; if TRUE, prints progress message.

Value

A data frame with encoded variables. For one-hot encoding, original categorical columns are replaced by binary columns.

Examples

# Label encoding
encode_categorical(data[1:100, c(1, 4)], cols = 2, method = "label")
# One-hot encoding
encode_categorical(data[1:100, c(1, 4)], cols = 2, method = "onehot")

dataprep documentation built on Oct. 1, 2026, 5:07 p.m.