Skip to content

Shift values by the given number of indices

Description

Shift values by the given number of indices

Usage

<Expr>$shift(n = 1, ..., fill_value = NULL)

Arguments

n Number of indices to shift forward. If a negative value is passed, values are shifted in the opposite direction instead.
These dots are for future extensions and must be empty.
fill_value Fill the resulting null values with this value.

Value

A polars expression

Examples

library("polars")

# By default, values are shifted forward by one index.
df <- pl$DataFrame(a = 1:4)
df$with_columns(shift = pl$col("a")$shift())
#> shape: (4, 2)
#> ┌─────┬───────┐
#> │ a   ┆ shift │
#> │ --- ┆ ---   │
#> │ i32 ┆ i32   │
#> ╞═════╪═══════╡
#> │ 1   ┆ null  │
#> │ 2   ┆ 1     │
#> │ 3   ┆ 2     │
#> │ 4   ┆ 3     │
#> └─────┴───────┘
# Pass a negative value to shift in the opposite direction instead.
df$with_columns(shift = pl$col("a")$shift(-2))
#> shape: (4, 2)
#> ┌─────┬───────┐
#> │ a   ┆ shift │
#> │ --- ┆ ---   │
#> │ i32 ┆ i32   │
#> ╞═════╪═══════╡
#> │ 1   ┆ 3     │
#> │ 2   ┆ 4     │
#> │ 3   ┆ null  │
#> │ 4   ┆ null  │
#> └─────┴───────┘
# Specify fill_value to fill the resulting null values.
df$with_columns(shift = pl$col("a")$shift(-2, fill_value = 100))
#> shape: (4, 2)
#> ┌─────┬───────┐
#> │ a   ┆ shift │
#> │ --- ┆ ---   │
#> │ i32 ┆ f64   │
#> ╞═════╪═══════╡
#> │ 1   ┆ 3.0   │
#> │ 2   ┆ 4.0   │
#> │ 3   ┆ 100.0 │
#> │ 4   ┆ 100.0 │
#> └─────┴───────┘