Skip to content

Bin values by their position in sorted order

Source code

Description

[Experimental]

Usage

<Expr>$bin_ranks(
  ranks = NULL,
  ...,
  n_bins = NULL,
  labels = NULL,
  include_intervals = FALSE
)

Arguments

ranks Explicit non-decreasing cumulative fractions in \[0, 1\].
… These dots are for future extensions and must be empty.
n_bins Number of near-equal-sized bins. Supply exactly one of ranks 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.

Value

A polars expression

Examples

library("polars")

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