Skip to content

Apply a rolling median over values

Description

[Experimental]

A window of length window_size will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the weights vector. The resulting values will be aggregated.

The window at a given row will include the row itself, and the window_size - 1 elements before it.

Usage

<Expr>$rolling_median(
  window_size,
  weights = NULL,
  ...,
  min_periods = NULL,
  center = FALSE
)

Arguments

window_size The length of the window in number of elements.
weights An optional slice with the same length as the window that will be multiplied elementwise with the values in the window.
These dots are for future extensions and must be empty.
min_periods 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 = 1:6)
df$with_columns(
  rolling_median = pl$col("a")$rolling_median(window_size = 2)
)
#> shape: (6, 2)
#> ┌─────┬────────────────┐
#> │ a   ┆ rolling_median │
#> │ --- ┆ ---            │
#> │ i32 ┆ f64            │
#> ╞═════╪════════════════╡
#> │ 1   ┆ null           │
#> │ 2   ┆ 1.5            │
#> │ 3   ┆ 2.5            │
#> │ 4   ┆ 3.5            │
#> │ 5   ┆ 4.5            │
#> │ 6   ┆ 5.5            │
#> └─────┴────────────────┘
# Specify weights to multiply the values in the window with:
df$with_columns(
  rolling_median = pl$col("a")$rolling_median(
    window_size = 2, weights = c(0.25, 0.75)
  )
)
#> shape: (6, 2)
#> ┌─────┬────────────────┐
#> │ a   ┆ rolling_median │
#> │ --- ┆ ---            │
#> │ i32 ┆ f64            │
#> ╞═════╪════════════════╡
#> │ 1   ┆ null           │
#> │ 2   ┆ 1.5            │
#> │ 3   ┆ 2.5            │
#> │ 4   ┆ 3.5            │
#> │ 5   ┆ 4.5            │
#> │ 6   ┆ 5.5            │
#> └─────┴────────────────┘
# Center the values in the window
df$with_columns(
  rolling_median = pl$col("a")$rolling_median(window_size = 3, center = TRUE)
)
#> shape: (6, 2)
#> ┌─────┬────────────────┐
#> │ a   ┆ rolling_median │
#> │ --- ┆ ---            │
#> │ i32 ┆ f64            │
#> ╞═════╪════════════════╡
#> │ 1   ┆ null           │
#> │ 2   ┆ 2.0            │
#> │ 3   ┆ 3.0            │
#> │ 4   ┆ 4.0            │
#> │ 5   ┆ 5.0            │
#> │ 6   ┆ null           │
#> └─────┴────────────────┘