Skip to content

Unpivot a Frame from wide to long format

Source code

Description

Unpivot a Frame from wide to long format

Usage

<LazyFrame>$melt(
  id_vars = NULL,
  value_vars = NULL,
  variable_name = NULL,
  value_name = NULL,
  ...,
  streamable = TRUE
)

Arguments

id_vars Columns to use as identifier variables.
value_vars Values to use as identifier variables. If value_vars is empty all columns that are not in id_vars will be used.
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"
Not used.
streamable Allow this node to run in the streaming engine. If this runs in streaming, the output of the melt operation will not have a stable ordering.

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$melt(id_vars = "a", value_vars = 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   │
#> └─────┴──────────┴───────┘