Sort this expression
Description
If used in a groupby context, values within each group are sorted.
Usage
<Expr>$sort(..., descending = FALSE, nulls_last = FALSE)
Arguments
…
|
These dots are for future extensions and must be empty. |
descending
|
Sort in descending order. |
nulls_last
|
Place null values last. |
Value
A polars expression
Examples
library("polars")
df <- pl$DataFrame(a = c(6, 1, 0, NA, Inf, NaN))
df$with_columns(
sorted = pl$col("a")$sort(),
sorted_desc = pl$col("a")$sort(descending = TRUE),
sorted_nulls_last = pl$col("a")$sort(nulls_last = TRUE)
)
#> shape: (6, 4)
#> ┌──────┬────────┬─────────────┬───────────────────┐
#> │ a ┆ sorted ┆ sorted_desc ┆ sorted_nulls_last │
#> │ --- ┆ --- ┆ --- ┆ --- │
#> │ f64 ┆ f64 ┆ f64 ┆ f64 │
#> ╞══════╪════════╪═════════════╪═══════════════════╡
#> │ 6.0 ┆ null ┆ null ┆ 0.0 │
#> │ 1.0 ┆ 0.0 ┆ NaN ┆ 1.0 │
#> │ 0.0 ┆ 1.0 ┆ inf ┆ 6.0 │
#> │ null ┆ 6.0 ┆ 6.0 ┆ inf │
#> │ inf ┆ inf ┆ 1.0 ┆ NaN │
#> │ NaN ┆ NaN ┆ 0.0 ┆ null │
#> └──────┴────────┴─────────────┴───────────────────┘
# When sorting in a group by context, values in each group are sorted.
df <- pl$DataFrame(
group = c("one", "one", "one", "two", "two", "two"),
value = c(1, 98, 2, 3, 99, 4)
)
df$group_by("group")$agg(pl$col("value")$sort())
#> shape: (2, 2)
#> ┌───────┬──────────────────┐
#> │ group ┆ value │
#> │ --- ┆ --- │
#> │ str ┆ list[f64] │
#> ╞═══════╪══════════════════╡
#> │ two ┆ [3.0, 4.0, 99.0] │
#> │ one ┆ [1.0, 2.0, 98.0] │
#> └───────┴──────────────────┘