R/trans_categ_mapping.R

Defines functions transform.categ_mapping categ_mapping

Documented in categ_mapping

#'@title Categorical mapping
#'@description Categorical mapping provides a way to map the levels of a categorical variable to new values.
#' Each possible value is converted to a binary attribute.
#'@param attribute attribute to be categorized.
#'@return A data frame with binary attributes, one for each possible category.
#'@examples
#'cm <- categ_mapping("Species")
#'iris_cm <- transform(cm, iris)
#'
#'# can be made in a single column
#'species <- iris[,"Species", drop=FALSE]
#'iris_cm <- transform(cm, species)
#'@export
categ_mapping <- function(attribute) {
  obj <- dal_transform()
  obj$attribute <- attribute
  class(obj) <- append("categ_mapping", class(obj))
  return(obj)
}

#'@importFrom stats formula
#'@importFrom stats model.matrix
#'@export
transform.categ_mapping <- function(obj, data, ...) {
  mdlattribute <- stats::formula(paste("~", paste(obj$attribute, "-1")))
  data <- as.data.frame(stats::model.matrix(mdlattribute, data=data))
  data[,obj$attribute] <- NULL
  return(data)
}

Try the daltoolbox package in your browser

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

daltoolbox documentation built on May 29, 2024, 1:57 a.m.