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(..., fields = NULL, n_field_strategy = deprecated())

Arguments

A character vector of field names can be supplied as the first positional argument. Scalar “first_non_null” and “max_width” values are interpreted as legacy n_field_strategy; use fields = … when either is a field name. Additional positional arguments are deprecated compatibility arguments.
fields Character vector of field names. NULL (default) and function-valued fields are deprecated; use an explicit character vector, which will be required in Polars 2.0.
n_field_strategy [Deprecated] 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 fields argument is character, this argument will be ignored.

Value

A polars Series

See Also

  • \$list$to_struct()

Examples

library("polars")

# Convert list to struct with explicit field names:
s1 <- as_polars_series(list(0:2, 0:1))
s2 <- s1$list$to_struct(c("one", "two", "three"))
s2
#> shape: (2, 1)
#> ┌────────────┐
#> │            │
#> │ ---        │
#> │ struct[3]  │
#> ╞════════════╡
#> │ {0,1,2}    │
#> │ {0,1,null} │
#> └────────────┘
s2$struct$fields
#> [1] "one"   "two"   "three"
# Dynamic field-name functions are deprecated:
s3 <- s1$list$to_struct(fields = \(idx) sprintf("n%02d", idx))
s3$struct$fields
#> [1] "n00" "n01" "n02"
# 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  │
#> └─────┴─────┴───────┘