Bin values into discrete intervals delimited by breakpoints
Description
Usage
<Expr>$bin_intervals(
intervals = NULL,
...,
n_bins = NULL,
labels = NULL,
include_intervals = FALSE,
right_closed = FALSE
)
Arguments
intervals
|
Explicit numeric breakpoints for the bin boundaries. |
…
|
These dots are for future extensions and must be empty. |
n_bins
|
Number of equal-width bins. Supply exactly one of intervals
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_intervals(
intervals = c(-1, 1), labels = c("low", "mid", "high"), right_closed = TRUE
))
#> shape: (5, 1)
#> ┌──────┐
#> │ bin │
#> │ --- │
#> │ enum │
#> ╞══════╡
#> │ low │
#> │ low │
#> │ mid │
#> │ mid │
#> │ high │
#> └──────┘
# A single integer is a breakpoint; use n_bins for equal-width bins.
df$select(bin = pl$col("foo")$bin_intervals(intervals = 2L, labels = NULL))
#> shape: (5, 1)
#> ┌─────┐
#> │ bin │
#> │ --- │
#> │ u32 │
#> ╞═════╡
#> │ 0 │
#> │ 0 │
#> │ 0 │
#> │ 0 │
#> │ 1 │
#> └─────┘
#> shape: (5, 1)
#> ┌─────┐
#> │ bin │
#> │ --- │
#> │ u32 │
#> ╞═════╡
#> │ 0 │
#> │ 0 │
#> │ 1 │
#> │ 2 │
#> │ 2 │
#> └─────┘