Skip to content

Bin values into discrete intervals delimited by their quantiles

Source code

Description

[Experimental]

Usage

<Expr>$bin_quantiles(
  quantiles = NULL,
  ...,
  n_bins = NULL,
  labels = NULL,
  include_intervals = FALSE,
  right_closed = FALSE
)

Arguments

quantiles Explicit non-decreasing quantile probabilities in \[0, 1\].
… These dots are for future extensions and must be empty.
n_bins Number of bins based on evenly spaced quantile fractions. Supply exactly one of quantiles and n_bins.
labels Names of the bins. The number of labels must equal the number of bins. Use NULL to return UInt32 bin indices.
include_intervals Return a struct with the bin and its left and right boundaries.
right_closed Use right-closed (left, right\] bins instead of left-closed \[left, right) bins.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(foo = -2:2)
df$select(bin = pl$col("foo")$bin_quantiles(
  quantiles = c(0.25, 0.75), labels = c("low", "mid", "high")
))
#> shape: (5, 1)
#> ┌──────┐
#> │ bin  │
#> │ ---  │
#> │ enum │
#> ╞══════╡
#> │ low  │
#> │ mid  │
#> │ mid  │
#> │ high │
#> │ high │
#> └──────┘
df$select(bin = pl$col("foo")$bin_quantiles(n_bins = 3, labels = NULL))
#> shape: (5, 1)
#> ┌─────┐
#> │ bin │
#> │ --- │
#> │ u32 │
#> ╞═════╡
#> │ 0   │
#> │ 1   │
#> │ 2   │
#> │ 2   │
#> │ 2   │
#> └─────┘