Skip to content

Check if an expression is between the given lower and upper bounds

Source code

Description

Check if an expression is between the given lower and upper bounds

Usage

<Expr>$is_between(lower_bound, upper_bound, closed = "both")

Arguments

lower_bound Lower bound, can be an Expr. Strings are parsed as column names.
upper_bound Upper bound, can be an Expr. Strings are parsed as column names.
closed Define which sides of the interval are closed (inclusive). This can be either “left”, “right”, “both” or “none”.

Details

Note that in polars, NaN are equal to other NaNs, and greater than any non-NaN value.

Value

Expr

Examples

library("polars")

df = pl$DataFrame(num = 1:5)
df$with_columns(
  is_between = pl$col("num")$is_between(2, 4),
  is_between_excl_upper = pl$col("num")$is_between(2, 4, closed = "left"),
  is_between_excl_both = pl$col("num")$is_between(2, 4, closed = "none")
)
#> shape: (5, 4)
#> ┌─────┬────────────┬───────────────────────┬──────────────────────┐
#> │ num ┆ is_between ┆ is_between_excl_upper ┆ is_between_excl_both │
#> │ --- ┆ ---        ┆ ---                   ┆ ---                  │
#> │ i32 ┆ bool       ┆ bool                  ┆ bool                 │
#> ╞═════╪════════════╪═══════════════════════╪══════════════════════╡
#> │ 1   ┆ false      ┆ false                 ┆ false                │
#> │ 2   ┆ true       ┆ true                  ┆ false                │
#> │ 3   ┆ true       ┆ true                  ┆ true                 │
#> │ 4   ┆ true       ┆ false                 ┆ false                │
#> │ 5   ┆ false      ┆ false                 ┆ false                │
#> └─────┴────────────┴───────────────────────┴──────────────────────┘
# lower and upper bounds can also be column names or expr
df = pl$DataFrame(
  num = 1:5,
  lower = c(0, 2, 3, 3, 3),
  upper = c(6, 4, 4, 8, 3.5)
)
df$with_columns(
  is_between_cols = pl$col("num")$is_between("lower", "upper"),
  is_between_expr = pl$col("num")$is_between(pl$col("lower") / 2, "upper")
)
#> shape: (5, 5)
#> ┌─────┬───────┬───────┬─────────────────┬─────────────────┐
#> │ num ┆ lower ┆ upper ┆ is_between_cols ┆ is_between_expr │
#> │ --- ┆ ---   ┆ ---   ┆ ---             ┆ ---             │
#> │ i32 ┆ f64   ┆ f64   ┆ bool            ┆ bool            │
#> ╞═════╪═══════╪═══════╪═════════════════╪═════════════════╡
#> │ 1   ┆ 0.0   ┆ 6.0   ┆ true            ┆ true            │
#> │ 2   ┆ 2.0   ┆ 4.0   ┆ true            ┆ true            │
#> │ 3   ┆ 3.0   ┆ 4.0   ┆ true            ┆ true            │
#> │ 4   ┆ 3.0   ┆ 8.0   ┆ true            ┆ true            │
#> │ 5   ┆ 3.0   ┆ 3.5   ┆ false           ┆ false           │
#> └─────┴───────┴───────┴─────────────────┴─────────────────┘