Skip to content

Folds the columns from left to right, keeping the first non-null value

Description

Folds the columns from left to right, keeping the first non-null value

Usage

pl$coalesce(...)

Arguments

\<dynamic-dots\> Non-named objects can be referenced as columns. Each object will be converted to expression by as_polars_expr(). Strings are parsed as column names, other non-expression inputs are parsed as literals.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(
  a = c(1, NA, NA, NA),
  b = c(1, 2, NA, NA),
  c = c(5, NA, 3, NA)
)

df$with_columns(d = pl$coalesce("a", "b", "c", 10))
#> shape: (4, 4)
#> ┌──────┬──────┬──────┬──────┐
#> │ a    ┆ b    ┆ c    ┆ d    │
#> │ ---  ┆ ---  ┆ ---  ┆ ---  │
#> │ f64  ┆ f64  ┆ f64  ┆ f64  │
#> ╞══════╪══════╪══════╪══════╡
#> │ 1.0  ┆ 1.0  ┆ 5.0  ┆ 1.0  │
#> │ null ┆ 2.0  ┆ null ┆ 2.0  │
#> │ null ┆ null ┆ 3.0  ┆ 3.0  │
#> │ null ┆ null ┆ null ┆ 10.0 │
#> └──────┴──────┴──────┴──────┘
df$with_columns(d = pl$coalesce(pl$col("a", "b", "c"), 10))
#> shape: (4, 4)
#> ┌──────┬──────┬──────┬──────┐
#> │ a    ┆ b    ┆ c    ┆ d    │
#> │ ---  ┆ ---  ┆ ---  ┆ ---  │
#> │ f64  ┆ f64  ┆ f64  ┆ f64  │
#> ╞══════╪══════╪══════╪══════╡
#> │ 1.0  ┆ 1.0  ┆ 5.0  ┆ 1.0  │
#> │ null ┆ 2.0  ┆ null ┆ 2.0  │
#> │ null ┆ null ┆ 3.0  ┆ 3.0  │
#> │ null ┆ null ┆ null ┆ 10.0 │
#> └──────┴──────┴──────┴──────┘