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
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 │
#> └─────┴─────┴─────┘