Skip to content

Cumulative count

Source code

Description

Get an array with the cumulative count (zero-indexed) computed at every element.

Usage

<Expr>$cum_count(reverse = FALSE)

Arguments

reverse If TRUE, reverse the count.

Details

The Dtypes Int8, UInt8, Int16 and UInt16 are cast to Int64 before summing to prevent overflow issues.

$cum_count() does not seem to count within lists.

Value

Expr

Examples

library(polars)

pl$DataFrame(a = 1:4)$with_columns(
  pl$col("a")$cum_count()$alias("cum_count"),
  pl$col("a")$cum_count(reverse = TRUE)$alias("cum_count_reversed")
)
#> shape: (4, 3)
#> ┌─────┬───────────┬────────────────────┐
#> │ a   ┆ cum_count ┆ cum_count_reversed │
#> │ --- ┆ ---       ┆ ---                │
#> │ i32 ┆ u32       ┆ u32                │
#> ╞═════╪═══════════╪════════════════════╡
#> │ 1   ┆ 1         ┆ 4                  │
#> │ 2   ┆ 2         ┆ 3                  │
#> │ 3   ┆ 3         ┆ 2                  │
#> │ 4   ┆ 4         ┆ 1                  │
#> └─────┴───────────┴────────────────────┘