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

series_list_to_struct(
  n_field_strategy = c("first_non_null", "max_width"),
  fields = NULL
)

Arguments

n_field_strategy One of “first_non_null” or “max_width”. Strategy to determine the number of fields of the struct.
  • “first_non_null” (default): Set number of fields equal to the length of the first non zero-length sublist.
  • “max_width”: Set number of fields as max length of all sublists.
If the field argument is character, this argument will be ignored.
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 Series

Examples

library("polars")

# Convert list to struct with default field name assignment:
s1 <- as_polars_series(list(0:2, 0:1))
s2 <- s1$list$to_struct()
s2
#> shape: (2, 1)
#> ┌────────────┐
#> │            │
#> │ ---        │
#> │ struct[3]  │
#> ╞════════════╡
#> │ {0,1,2}    │
#> │ {0,1,null} │
#> └────────────┘
s2$struct$fields
#> [1] "field_0" "field_1" "field_2"
# Convert list to struct with field name assignment by
# index from a list of names:
s1$list$to_struct(fields = c("one", "two", "three"))$struct$unnest()
#> shape: (2, 3)
#> ┌─────┬─────┬───────┐
#> │ one ┆ two ┆ three │
#> │ --- ┆ --- ┆ ---   │
#> │ i32 ┆ i32 ┆ i32   │
#> ╞═════╪═════╪═══════╡
#> │ 0   ┆ 1   ┆ 2     │
#> │ 0   ┆ 1   ┆ null  │
#> └─────┴─────┴───────┘