Skip to content

Calculate the n-th discrete difference between elements

Description

Calculate the n-th discrete difference between elements

Usage

<Expr>$diff(n = 1, null_behavior = c("ignore", "drop"))

Arguments

n Integer indicating the number of slots to shift.
null_behavior How to handle null values. Must be “ignore” (default), or “drop”.

Value

A polars expression

Examples

library("polars")

pl$DataFrame(a = c(20, 10, 30, 25, 35))$with_columns(
  diff_default = pl$col("a")$diff(),
  diff_2_ignore = pl$col("a")$diff(2, "ignore")
)
#> shape: (5, 3)
#> ┌──────┬──────────────┬───────────────┐
#> │ a    ┆ diff_default ┆ diff_2_ignore │
#> │ ---  ┆ ---          ┆ ---           │
#> │ f64  ┆ f64          ┆ f64           │
#> ╞══════╪══════════════╪═══════════════╡
#> │ 20.0 ┆ null         ┆ null          │
#> │ 10.0 ┆ -10.0        ┆ null          │
#> │ 30.0 ┆ 20.0         ┆ 10.0          │
#> │ 25.0 ┆ -5.0         ┆ 15.0          │
#> │ 35.0 ┆ 10.0         ┆ 5.0           │
#> └──────┴──────────────┴───────────────┘