Skip to content

Unpivot a Frame from wide to long format

Source code

Description

Unpivot a Frame from wide to long format

Usage

<LazyFrame>$unpivot(
  on = NULL,
  ...,
  index = NULL,
  variable_name = NULL,
  value_name = NULL
)

Arguments

on Values to use as identifier variables. If value_vars is empty all columns that are not in id_vars will be used.
Not used.
index Columns to use as identifier variables.
variable_name Name to give to the new column containing the names of the melted columns. Defaults to "variable".
value_name Name to give to the new column containing the values of the melted columns. Defaults to “value”.

Details

Optionally leaves identifiers set.

This function is useful to massage a Frame into a format where one or more columns are identifier variables (id_vars), while all other columns, considered measured variables (value_vars), are "unpivoted" to the row axis, leaving just two non-identifier columns, ‘variable’ and ‘value’.

Value

A LazyFrame

Examples

library("polars")

lf = pl$LazyFrame(
  a = c("x", "y", "z"),
  b = c(1, 3, 5),
  c = c(2, 4, 6)
)
lf$unpivot(index = "a", on = c("b", "c"))$collect()
#> shape: (6, 3)
#> ┌─────┬──────────┬───────┐
#> │ a   ┆ variable ┆ value │
#> │ --- ┆ ---      ┆ ---   │
#> │ str ┆ str      ┆ f64   │
#> ╞═════╪══════════╪═══════╡
#> │ x   ┆ b        ┆ 1.0   │
#> │ y   ┆ b        ┆ 3.0   │
#> │ z   ┆ b        ┆ 5.0   │
#> │ x   ┆ c        ┆ 2.0   │
#> │ y   ┆ c        ┆ 4.0   │
#> │ z   ┆ c        ┆ 6.0   │
#> └─────┴──────────┴───────┘