Skip to content

Collect columns into a list column

Source code

Description

Unlike pl$concat_list(), list-typed inputs are not extended: the value of each input becomes a single element of the output list. This means that List(T) inputs produce a List(List(T)) output.

Usage

pl$list(...)

Arguments

\<dynamic-dots\> Columns to collect into a list column. Accepts expression input. Strings are parsed as column names, other non-expression inputs are parsed as literals.

Value

A polars expression

Examples

library("polars")

# Wrap non-list columns into a list (same as pl$concat_list() in this case).
df <- pl$DataFrame(a = c(1, 2, 3), b = c(4, 5, 6))
df$with_columns(a_b = pl$list("a", "b"))
#> shape: (3, 3)
#> ┌─────┬─────┬────────────┐
#> │ a   ┆ b   ┆ a_b        │
#> │ --- ┆ --- ┆ ---        │
#> │ f64 ┆ f64 ┆ list[f64]  │
#> ╞═════╪═════╪════════════╡
#> │ 1.0 ┆ 4.0 ┆ [1.0, 4.0] │
#> │ 2.0 ┆ 5.0 ┆ [2.0, 5.0] │
#> │ 3.0 ┆ 6.0 ┆ [3.0, 6.0] │
#> └─────┴─────┴────────────┘
# Collect list columns into a list of lists. pl$concat_list() would instead
# concatenate them into a single list.
df <- pl$DataFrame(a = list(1:2, 3L, 4:5), b = list(6L, 7:8, 9L))
df$with_columns(
  list = pl$list("a", "b"),
  concat_list = pl$concat_list("a", "b")
)
#> shape: (3, 4)
#> ┌───────────┬───────────┬─────────────────┬─────────────┐
#> │ a         ┆ b         ┆ list            ┆ concat_list │
#> │ ---       ┆ ---       ┆ ---             ┆ ---         │
#> │ list[i32] ┆ list[i32] ┆ list[list[i32]] ┆ list[i32]   │
#> ╞═══════════╪═══════════╪═════════════════╪═════════════╡
#> │ [1, 2]    ┆ [6]       ┆ [[1, 2], [6]]   ┆ [1, 2, 6]   │
#> │ [3]       ┆ [7, 8]    ┆ [[3], [7, 8]]   ┆ [3, 7, 8]   │
#> │ [4, 5]    ┆ [9]       ┆ [[4, 5], [9]]   ┆ [4, 5, 9]   │
#> └───────────┴───────────┴─────────────────┴─────────────┘