Skip to content

Convert the Series of type List to a Series of type Struct

Source code

Description

Convert the Series of type List to a Series of type Struct

Usage

<Expr>$list$to_struct(fields)

Arguments

fields A character vector of field names.

Details

The field names must be supplied explicitly.

Value

A polars expression

See Also

  • \$arr$to_struct()
  • \$list$to_struct()

Examples

library("polars")

df <- pl$DataFrame(n = list(c(0, 1), c(0, 1, 2)))

# Convert list to struct with explicit field names:

df$select(pl$col("n")$list$to_struct(c("one", "two", "three")))$unnest("n")
#> shape: (2, 3)
#> ┌─────┬─────┬───────┐
#> │ one ┆ two ┆ three │
#> │ --- ┆ --- ┆ ---   │
#> │ f64 ┆ f64 ┆ f64   │
#> ╞═════╪═════╪═══════╡
#> │ 0.0 ┆ 1.0 ┆ null  │
#> │ 0.0 ┆ 1.0 ┆ 2.0   │
#> └─────┴─────┴───────┘
# Convert list to struct with field name assignment by
# index from a list of names:
df$select(pl$col("n")$list$to_struct(
  fields = c("one", "two", "three"))
)$unnest("n")
#> shape: (2, 3)
#> ┌─────┬─────┬───────┐
#> │ one ┆ two ┆ three │
#> │ --- ┆ --- ┆ ---   │
#> │ f64 ┆ f64 ┆ f64   │
#> ╞═════╪═════╪═══════╡
#> │ 0.0 ┆ 1.0 ┆ null  │
#> │ 0.0 ┆ 1.0 ┆ 2.0   │
#> └─────┴─────┴───────┘