cut_quantile_bins: Cut numeric vector into empirical quantile bins

View source: R/utils_factor.R

cut_quantile_binsR Documentation

Cut numeric vector into empirical quantile bins

Description

[Stable]

This cuts a numeric vector into sample quantile bins.

Usage

cut_quantile_bins(
  x,
  probs = c(0.25, 0.5, 0.75),
  labels = NULL,
  type = 7,
  ordered = TRUE
)

Arguments

x

(numeric)
the continuous variable values which should be cut into quantile bins. This may contain NA values, which are then not used for the quantile calculations, but included in the return vector.

probs

(numeric)
the probabilities identifying the quantiles. This is a sorted vector of unique proportion values, i.e. between 0 and 1, where the boundaries 0 and 1 must not be included.

labels

(character)
the unique labels for the quantile bins. When there are n probabilities in probs, then this must be n + 1 long.

type

(integer(1))
type of quantiles to use, see stats::quantile() for details.

ordered

(flag)
should the result be an ordered factor.

Value

A factor variable with appropriately-labeled bins as levels.

Note

Intervals are closed on the right side. That is, the first bin is the interval ⁠[-Inf, q1]⁠ where q1 is the first quantile, the second bin is then ⁠(q1, q2]⁠, etc., and the last bin is ⁠(qn, +Inf]⁠ where qn is the last quantile.

Examples

# Default is to cut into quartile bins.
cut_quantile_bins(cars$speed)

# Use custom quantiles.
cut_quantile_bins(cars$speed, probs = c(0.1, 0.2, 0.6, 0.88))

# Use custom labels.
cut_quantile_bins(cars$speed, labels = paste0("Q", 1:4))

# NAs are preserved in result factor.
ozone_binned <- cut_quantile_bins(airquality$Ozone)
which(is.na(ozone_binned))
# So you might want to make these explicit.
explicit_na(ozone_binned)


tern documentation built on Sept. 24, 2024, 9:06 a.m.