Skip to content

Compute difference between list values

Source code

Description

This computes the first discrete difference between shifted items of every list. The parameter n gives the interval between items to subtract, e.g n = 2 the output will be the difference between the 1st and the 3rd value, the 2nd and 4th value, etc.

Usage

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

Arguments

n Number of slots to shift. If negative, then it starts from the end.
null_behavior How to handle null values. Either “ignore” (default) or “drop”.

Value

Expr

Examples

library("polars")

df = pl$DataFrame(list(s = list(1:4, c(10L, 2L, 1L))))
df$with_columns(diff = pl$col("s")$list$diff(2))
#> shape: (2, 2)
#> ┌─────────────┬───────────────────┐
#> │ s           ┆ diff              │
#> │ ---         ┆ ---               │
#> │ list[i32]   ┆ list[i32]         │
#> ╞═════════════╪═══════════════════╡
#> │ [1, 2, … 4] ┆ [null, null, … 2] │
#> │ [10, 2, 1]  ┆ [null, null, -9]  │
#> └─────────────┴───────────────────┘
# negative value starts shifting from the end
df$with_columns(diff = pl$col("s")$list$diff(-2))
#> shape: (2, 2)
#> ┌─────────────┬──────────────────┐
#> │ s           ┆ diff             │
#> │ ---         ┆ ---              │
#> │ list[i32]   ┆ list[i32]        │
#> ╞═════════════╪══════════════════╡
#> │ [1, 2, … 4] ┆ [-2, -2, … null] │
#> │ [10, 2, 1]  ┆ [9, null, null]  │
#> └─────────────┴──────────────────┘