Skip to content

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

Description

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

Usage

<Expr>$arr$to_struct(fields = NULL)

Arguments

fields [Experimental] NULL (default) or character vector of field names, or a function that takes an integer index and returns character. If the name and number of the desired fields is known in advance, character vector of field names can be given, which will be assigned by index. Otherwise, to dynamically assign field names, a custom function can be used; if neither are set, fields will be field_0, field_1… See the examples for details.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(
  n = list(c(0, 1, 2), c(3, 4, 5)),
  .schema_overrides = list(n = pl$Array(pl$Int8, 3))
)

df$with_columns(struct = pl$col("n")$arr$to_struct())
#> shape: (2, 2)
#> ┌──────────────┬───────────┐
#> │ n            ┆ struct    │
#> │ ---          ┆ ---       │
#> │ array[i8, 3] ┆ struct[3] │
#> ╞══════════════╪═══════════╡
#> │ [0, 1, 2]    ┆ {0,1,2}   │
#> │ [3, 4, 5]    ┆ {3,4,5}   │
#> └──────────────┴───────────┘
# Convert array to struct with field name assignment by function/index:
df$select(pl$col("n")$arr$to_struct(\(idx) paste0("n", idx)))$unnest("n")
#> shape: (2, 3)
#> ┌─────┬─────┬─────┐
#> │ n0  ┆ n1  ┆ n2  │
#> │ --- ┆ --- ┆ --- │
#> │ i8  ┆ i8  ┆ i8  │
#> ╞═════╪═════╪═════╡
#> │ 0   ┆ 1   ┆ 2   │
#> │ 3   ┆ 4   ┆ 5   │
#> └─────┴─────┴─────┘
# Convert array to struct with field name assignment by index from character:
df$select(pl$col("n")$arr$to_struct(c("a", "b", "c")))$unnest("n")
#> shape: (2, 3)
#> ┌─────┬─────┬─────┐
#> │ a   ┆ b   ┆ c   │
#> │ --- ┆ --- ┆ --- │
#> │ i8  ┆ i8  ┆ i8  │
#> ╞═════╪═════╪═════╡
#> │ 0   ┆ 1   ┆ 2   │
#> │ 3   ┆ 4   ┆ 5   │
#> └─────┴─────┴─────┘