Skip to content

Horizontally concatenate columns into a single string column

Source code

Description

Horizontally concatenate columns into a single string column

Usage

pl$concat_str(..., separator = "", ignore_nulls = FALSE)

Arguments

Columns to concatenate into a single string column. Accepts expressions. Strings are parsed as column names, other non-expression inputs are parsed as literals. Non-String columns are cast to String
separator String that will be used to separate the values of each column.
ignore_nulls If FALSE (default), null values are propagated: if the row contains any null values, the output is null.

Value

Expr

Examples

library("polars")

df = pl$DataFrame(
  a = 1:3,
  b = c("dogs", "cats", NA),
  c = c("play", "swim", "walk")
)

df$with_columns(
  pl$concat_str(
    pl$col("a") * 2L, "b", "c", pl$lit("!"),
    separator = " "
  )$alias("full_sentence")
)
#> shape: (3, 4)
#> ┌─────┬──────┬──────┬───────────────┐
#> │ a   ┆ b    ┆ c    ┆ full_sentence │
#> │ --- ┆ ---  ┆ ---  ┆ ---           │
#> │ i32 ┆ str  ┆ str  ┆ str           │
#> ╞═════╪══════╪══════╪═══════════════╡
#> │ 1   ┆ dogs ┆ play ┆ 2 dogs play ! │
#> │ 2   ┆ cats ┆ swim ┆ 4 cats swim ! │
#> │ 3   ┆ null ┆ walk ┆ null          │
#> └─────┴──────┴──────┴───────────────┘
df$with_columns(
  pl$concat_str(
    pl$col("a") * 2L, "b", "c", pl$lit("!"),
    separator = " ",
    ignore_nulls = TRUE
  )$alias("full_sentence")
)
#> shape: (3, 4)
#> ┌─────┬──────┬──────┬───────────────┐
#> │ a   ┆ b    ┆ c    ┆ full_sentence │
#> │ --- ┆ ---  ┆ ---  ┆ ---           │
#> │ i32 ┆ str  ┆ str  ┆ str           │
#> ╞═════╪══════╪══════╪═══════════════╡
#> │ 1   ┆ dogs ┆ play ┆ 2 dogs play ! │
#> │ 2   ┆ cats ┆ swim ┆ 4 cats swim ! │
#> │ 3   ┆ null ┆ walk ┆ 6 walk !      │
#> └─────┴──────┴──────┴───────────────┘