R/trans_one_hot.R

Defines functions transform.one_hot fit.one_hot one_hot

Documented in one_hot

#' @title One-hot encoding (fitted)
#' @description A [daltoolbox::dal_transform()] that one-hot encodes the categorical columns (factor,
#'  character or logical) of a data frame. It learns the categories at `fit()` and, at `transform()`,
#'  always produces the same columns: a category absent from a batch becomes a zero column and an
#'  unseen category is ignored. Numeric columns are kept unchanged. It is the default first step of
#'  the preprocessing of [adp_recurrent()].
#' @return A `one_hot` object.
#' @examples
#' library(daltoolbox)
#' oh <- fit(one_hot(), iris)
#' head(transform(oh, iris))
#' @import daltoolbox
#' @export
one_hot <- function() {
  obj <- dal_transform()
  obj$encoder <- NULL
  class(obj) <- append("one_hot", class(obj))
  obj
}

#' @export
fit.one_hot <- function(obj, data, ...) {
  obj$encoder <- .one_hot_fit(as.data.frame(data))
  obj
}

#' @export
transform.one_hot <- function(obj, data, ...) {
  if (is.null(obj$encoder)) stop("one_hot: call fit() before transform().", call. = FALSE)
  .one_hot_apply(obj$encoder, as.data.frame(data))
}

Try the heimdall package in your browser

Any scripts or data that you put into this service are public.

heimdall documentation built on Dec. 2, 2026, 5:08 p.m.