Check if an expression is between the given lower and upper bounds
Description
Check if an expression is between the given lower and upper bounds
Usage
<Expr>$is_between(
lower_bound,
upper_bound,
closed = c("both", "left", "right", "none")
)
Arguments
lower_bound
|
Lower bound value. Accepts expression input. Strings are parsed as column names, other non-expression inputs are parsed as literals. |
upper_bound
|
Upper bound value. Accepts expression input. Strings are parsed as column names, other non-expression inputs are parsed as literals. |
closed
|
Define which sides of the interval are closed (inclusive). Must be one
of “left” , “right” , “both” or
“none” .
|
Details
If the value of the lower_bound
is greater than that of the
upper_bound
then the result will be FALSE
, as
no value can satisfy the condition.
Value
A polars expression
Examples
library("polars")
df <- pl$DataFrame(num = 1:5)
df$with_columns(
is_between = pl$col("num")$is_between(2, 4)
)
#> shape: (5, 2)
#> ┌─────┬────────────┐
#> │ num ┆ is_between │
#> │ --- ┆ --- │
#> │ i32 ┆ bool │
#> ╞═════╪════════════╡
#> │ 1 ┆ false │
#> │ 2 ┆ true │
#> │ 3 ┆ true │
#> │ 4 ┆ true │
#> │ 5 ┆ false │
#> └─────┴────────────┘
# Use the closed argument to include or exclude the values at the bounds:
df$with_columns(
is_between = pl$col("num")$is_between(2, 4, closed = "left")
)
#> shape: (5, 2)
#> ┌─────┬────────────┐
#> │ num ┆ is_between │
#> │ --- ┆ --- │
#> │ i32 ┆ bool │
#> ╞═════╪════════════╡
#> │ 1 ┆ false │
#> │ 2 ┆ true │
#> │ 3 ┆ true │
#> │ 4 ┆ false │
#> │ 5 ┆ false │
#> └─────┴────────────┘
# You can also use strings as well as numeric/temporal values (note: ensure
# that string literals are wrapped with lit so as not to conflate them with
# column names):
df <- pl$DataFrame(a = letters[1:5])
df$with_columns(
is_between = pl$col("a")$is_between(pl$lit("a"), pl$lit("c"))
)
#> shape: (5, 2)
#> ┌─────┬────────────┐
#> │ a ┆ is_between │
#> │ --- ┆ --- │
#> │ str ┆ bool │
#> ╞═════╪════════════╡
#> │ a ┆ true │
#> │ b ┆ true │
#> │ c ┆ true │
#> │ d ┆ false │
#> │ e ┆ false │
#> └─────┴────────────┘
# Use column expressions as lower/upper bounds, comparing to a literal value:
df <- pl$DataFrame(a = 1:5, b = 5:1)
df$with_columns(
between_ab = pl$lit(3)$is_between(pl$col("a"), pl$col("b"))
)
#> shape: (5, 3)
#> ┌─────┬─────┬────────────┐
#> │ a ┆ b ┆ between_ab │
#> │ --- ┆ --- ┆ --- │
#> │ i32 ┆ i32 ┆ bool │
#> ╞═════╪═════╪════════════╡
#> │ 1 ┆ 5 ┆ true │
#> │ 2 ┆ 4 ┆ true │
#> │ 3 ┆ 3 ┆ true │
#> │ 4 ┆ 2 ┆ false │
#> │ 5 ┆ 1 ┆ false │
#> └─────┴─────┴────────────┘