Skip to content

Apply a rolling rank over values

Source code

Description

[Experimental]

A window of length window_size will traverse the array. The values that fill this window will be ranked according to the method parameter. The resulting values will be the rank of the value that is at the end of the sliding window.

Usage

<Expr>$rolling_rank(
  window_size,
  method = c("average", "min", "max", "dense", "random"),
  ...,
  seed = NULL,
  min_samples = NULL,
  center = FALSE
)

Arguments

window_size The length of the window in number of elements.
method The method used to assign ranks to tied elements. Must be one of the following:
  • “average” (default): The average of the ranks that would have been assigned to all the tied values is assigned to each value.
  • “min”: The minimum of the ranks that would have been assigned to all the tied values is assigned to each value. (This is also referred to as "competition" ranking.)
  • “max”: The maximum of the ranks that would have been assigned to all the tied values is assigned to each value.
  • “dense”: Like “min”, but the rank of the next highest element is assigned the rank immediately after those assigned to the tied elements.
  • “random”: Choose a random rank for each value in a tie.
These dots are for future extensions and must be empty.
seed Random seed used when method = “random”. If NULL (default), a random seed is generated for each rolling rank operation.
min_samples The number of values in the window that should be non-null before computing a result. If NULL (default), it will be set equal to window_size.
center If TRUE, set the labels at the center of the window.

Details

If you want to compute multiple aggregation statistics over the same dynamic window, consider using $rolling() - this method can cache the window size computation.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(a = c(1, 4, 4, 1, 9))

df$select(pl$col("a")$rolling_rank(3, method = "average"))
#> shape: (5, 1)
#> ┌──────┐
#> │ a    │
#> │ ---  │
#> │ f64  │
#> ╞══════╡
#> │ null │
#> │ null │
#> │ 2.5  │
#> │ 1.0  │
#> │ 3.0  │
#> └──────┘