bin_data: Discretize continuous variables into bins

View source: R/bin_data.R

bin_dataR Documentation

Discretize continuous variables into bins

Description

Converts numeric columns into categorical factors using equal-width, equal-frequency, or custom breakpoints. This is a common preprocessing step for transforming continuous variables for modeling or visualization.

Usage

bin_data(data, cols = NULL, method = "equal_width", 
         bins = 10, breaks = NULL, include_lowest = TRUE,
         labels = NULL, verbose = FALSE)

Arguments

data

A data frame containing numeric columns to bin.

cols

Column indices or names to bin. If NULL, all numeric columns are used.

method

Binning method. One of "equal_width", "equal_freq", or "custom".

bins

Number of bins for equal-width and equal-frequency methods.

breaks

Numeric vector of breakpoints for custom binning. Required when method = "custom".

labels

Optional character vector of labels for the bins.

include_lowest

Logical; if TRUE, the lowest break value is included in the first bin.

verbose

Logical; if TRUE, prints a timing message.

Details

For "equal_width", bins are created by dividing the range of the data into equal-width intervals. For "equal_freq", bins are created by quantiles so that each bin contains approximately the same number of observations. The "custom" method uses user-supplied breakpoints.

Missing values are preserved as NA in the output.

Value

If data is a data frame, a data frame with the selected columns replaced by factors. If data is a numeric vector, a factor vector.

Examples

data <- data.frame(x = rnorm(100), y = runif(100))
# Equal-width binning into 5 bins
bin_data(data, cols = 1:2, bins = 5)

# Equal-frequency binning
bin_data(data, cols = "x", method = "equal_freq", bins = 4)

# Custom breaks
bin_data(data, cols = "x", method = "custom", breaks = c(-Inf, 0, Inf), labels = c("neg", "pos"))

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