| bin_data | R Documentation |
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.
bin_data(data, cols = NULL, method = "equal_width",
bins = 10, breaks = NULL, include_lowest = TRUE,
labels = NULL, verbose = FALSE)
data |
A data frame containing numeric columns to bin. |
cols |
Column indices or names to bin. If |
method |
Binning method. One of |
bins |
Number of bins for equal-width and equal-frequency methods. |
breaks |
Numeric vector of breakpoints for custom binning. Required when |
labels |
Optional character vector of labels for the bins. |
include_lowest |
Logical; if |
verbose |
Logical; if |
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.
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.
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"))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.