Skip to content

Return the row indices that would sort the columns

Source code

Description

Return the row indices that would sort the columns

Usage

pl$arg_sort_by(
  ...,
  descending = FALSE,
  nulls_last = FALSE,
  multithreaded = TRUE,
  maintain_order = FALSE
)

Arguments

Column(s) to arg sort by. Can be Expr(s) or something coercible to Expr(s). Strings are parsed as column names.
descending Logical. Sort in descending order (default is FALSE). This must be either of length 1 or a logical vector of the same length as the number of Expr(s) specified in by and .
nulls_last A logical or logical vector of the same length as the number of columns. If TRUE, place null values last insead of first.
multithreaded A logical. If TRUE, sort using multiple threads.
maintain_order Whether the order should be maintained if elements are equal. If TRUE, streaming is not possible and performance might be worse since this requires a stable search.

Value

Expr

See Also

$arg_sort() to find the row indices that would sort an Expr.

Examples

library(polars)

df = pl$DataFrame(
  a = c(0, 1, 1, 0),
  b = c(3, 2, 3, 2)
)

df$with_columns(
  arg_sort_a = pl$arg_sort_by("a"),
  arg_sort_ab = pl$arg_sort_by(c("a", "b"), descending = TRUE)
)
#> shape: (4, 4)
#> ┌─────┬─────┬────────────┬─────────────┐
#> │ a   ┆ b   ┆ arg_sort_a ┆ arg_sort_ab │
#> │ --- ┆ --- ┆ ---        ┆ ---         │
#> │ f64 ┆ f64 ┆ u32        ┆ u32         │
#> ╞═════╪═════╪════════════╪═════════════╡
#> │ 0.0 ┆ 3.0 ┆ 0          ┆ 2           │
#> │ 1.0 ┆ 2.0 ┆ 3          ┆ 1           │
#> │ 1.0 ┆ 3.0 ┆ 1          ┆ 0           │
#> │ 0.0 ┆ 2.0 ┆ 2          ┆ 3           │
#> └─────┴─────┴────────────┴─────────────┘
# we can also pass Expr
df$with_columns(
  arg_sort_a = pl$arg_sort_by(pl$col("a") * -1)
)
#> shape: (4, 3)
#> ┌─────┬─────┬────────────┐
#> │ a   ┆ b   ┆ arg_sort_a │
#> │ --- ┆ --- ┆ ---        │
#> │ f64 ┆ f64 ┆ u32        │
#> ╞═════╪═════╪════════════╡
#> │ 0.0 ┆ 3.0 ┆ 1          │
#> │ 1.0 ┆ 2.0 ┆ 2          │
#> │ 1.0 ┆ 3.0 ┆ 0          │
#> │ 0.0 ┆ 2.0 ┆ 3          │
#> └─────┴─────┴────────────┘