Skip to content

Polars expression class (polars_expr)

Description

An expression is a tree of operations that describe how to construct one or more Series. As the outputs are Series, it is straightforward to apply a sequence of expressions each of which transforms the output from the previous step. See examples for details.

See Also

  • pl$lit(): Create a literal expression.
  • pl$col(): Create an expression representing column(s) in a DataFrame.

Examples

library("polars")

# An expression:
# 1. Select column `foo`,
# 2. Then sort the column (not in reversed order)
# 3. Then take the first two values of the sorted output
pl$col("foo")$sort()$head(2)
#> col("foo").sort(asc).slice(offset=0.0.cast(Int64), length=2.0.cast(Int64))
# Expressions will be evaluated inside a context, such as `<DataFrame>$select()`
df <- pl$DataFrame(
  foo = c(1, 2, 1, 2, 3),
  bar = c(5, 4, 3, 2, 1),
)

df$select(
  pl$col("foo")$sort()$head(3), # Return 3 values
  pl$col("bar")$filter(pl$col("foo") == 1)$sum(), # Return a single value
)
#> shape: (3, 2)
#> ┌─────┬─────┐
#> │ foo ┆ bar │
#> │ --- ┆ --- │
#> │ f64 ┆ f64 │
#> ╞═════╪═════╡
#> │ 1.0 ┆ 8.0 │
#> │ 1.0 ┆ 8.0 │
#> │ 2.0 ┆ 8.0 │
#> └─────┴─────┘