Skip to content

Unpivot a frame from wide to long format

Description

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

Usage

<DataFrame>$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.
These dots are for future extensions and must be empty.
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”.

Value

A polars LazyFrame

Examples

library("polars")

df <- pl$DataFrame(
  a = c("x", "y", "z"),
  b = c(1, 3, 5),
  c = c(2, 4, 6)
)
df$unpivot(index = "a", on = c("b", "c"))
#> 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   │
#> └─────┴──────────┴───────┘