one.hot: One Hot Encoder

View source: R/one.hot.R

one.hotR Documentation

One Hot Encoder

Description

One-hot encode categorical columns using base R. Character columns are converted to factors, with levels in order of first appearance.

Usage

one.hot(data, cols = "auto", sparsifyNAs = FALSE, naCols = FALSE,
        dropCols = FALSE, dropUnusedLevels = FALSE)

Arguments

data

A vector, matrix, data.frame, or data.table.

cols

Column names or positive integer column indices to encode. The default, "auto", selects all unordered factor columns after converting character columns to factors. Explicitly selected columns must be factors or character vectors. Use character(0) or NULL to select no columns.

sparsifyNAs

Logical. If TRUE, replace missing values in the generated level indicators with zeros. Otherwise, retain them as NA. Original columns are not affected.

naCols

Logical. If TRUE, add a missing-value indicator for each selected column containing missing values.

dropCols

Logical. If TRUE, drop the original encoded columns.

dropUnusedLevels

Logical. If TRUE, omit indicators for unused factor levels. Otherwise, include indicators for all factor levels.

Details

Level indicators are integer columns named column_level. They follow their original column in factor-level order. When requested, the missing-value indicator is named column_NA and precedes the level indicators. Ordered factors are excluded by cols = "auto", but can be selected explicitly. Original column order and row order are preserved. Input column names must be unique and non-empty. Encoding that would create duplicate column names produces an error; rename the relevant columns or factor levels.

The encoding itself requires no additional packages. The data.table package is required only when the input is a data.table.

Value

A data.frame, or a data.table when the input is a data.table. Vector and matrix inputs return a data.frame; a vector is treated as a single column named data. The input object is not modified.

Author(s)

Reza Mohammadi a.mohammadi@uva.nl

See Also

scaler

Examples

data(risk)
str(risk)
risk_one_hot <- one.hot(risk, cols = "auto")
str(risk_one_hot)

# Missing values and unused factor levels
example_data <- data.frame(
    color = factor(c("red", NA, "blue"), levels = c("blue", "green", "red"))
)
one.hot(example_data, sparsifyNAs = TRUE, naCols = TRUE,
        dropCols = TRUE, dropUnusedLevels = TRUE)

liver documentation built on Nov. 13, 2026, 5:06 p.m.