Skip to content

Group by the given columns and return the groups as separate dataframes

Description

Group by the given columns and return the groups as separate dataframes

Usage

<DataFrame>$partition_by(..., maintain_order = TRUE, include_key = TRUE)

Arguments

\<dynamic-dots\> Column name(s) to group by.
maintain_order Ensure that the order of the groups is consistent with the input data. This is slower than a default partition by operation.
include_key Include the columns used to partition the DataFrame in the output.

Value

A list of polars DataFrames

Examples

library("polars")

# Pass a single column name to partition by that column.
df <- pl$DataFrame(
  a = c("a", "b", "a", "b", "c"),
  b = c(1, 2, 1, 3, 3),
  c = c(5, 4, 3, 2, 1)
)
df$partition_by("a")
#> [[1]]
#> shape: (2, 3)
#> ┌─────┬─────┬─────┐
#> │ a   ┆ b   ┆ c   │
#> │ --- ┆ --- ┆ --- │
#> │ str ┆ f64 ┆ f64 │
#> ╞═════╪═════╪═════╡
#> │ a   ┆ 1.0 ┆ 5.0 │
#> │ a   ┆ 1.0 ┆ 3.0 │
#> └─────┴─────┴─────┘
#> 
#> [[2]]
#> shape: (2, 3)
#> ┌─────┬─────┬─────┐
#> │ a   ┆ b   ┆ c   │
#> │ --- ┆ --- ┆ --- │
#> │ str ┆ f64 ┆ f64 │
#> ╞═════╪═════╪═════╡
#> │ b   ┆ 2.0 ┆ 4.0 │
#> │ b   ┆ 3.0 ┆ 2.0 │
#> └─────┴─────┴─────┘
#> 
#> [[3]]
#> shape: (1, 3)
#> ┌─────┬─────┬─────┐
#> │ a   ┆ b   ┆ c   │
#> │ --- ┆ --- ┆ --- │
#> │ str ┆ f64 ┆ f64 │
#> ╞═════╪═════╪═════╡
#> │ c   ┆ 3.0 ┆ 1.0 │
#> └─────┴─────┴─────┘
# Partition by multiple columns:
df$partition_by("a", "b")
#> [[1]]
#> shape: (2, 3)
#> ┌─────┬─────┬─────┐
#> │ a   ┆ b   ┆ c   │
#> │ --- ┆ --- ┆ --- │
#> │ str ┆ f64 ┆ f64 │
#> ╞═════╪═════╪═════╡
#> │ a   ┆ 1.0 ┆ 5.0 │
#> │ a   ┆ 1.0 ┆ 3.0 │
#> └─────┴─────┴─────┘
#> 
#> [[2]]
#> shape: (1, 3)
#> ┌─────┬─────┬─────┐
#> │ a   ┆ b   ┆ c   │
#> │ --- ┆ --- ┆ --- │
#> │ str ┆ f64 ┆ f64 │
#> ╞═════╪═════╪═════╡
#> │ b   ┆ 2.0 ┆ 4.0 │
#> └─────┴─────┴─────┘
#> 
#> [[3]]
#> shape: (1, 3)
#> ┌─────┬─────┬─────┐
#> │ a   ┆ b   ┆ c   │
#> │ --- ┆ --- ┆ --- │
#> │ str ┆ f64 ┆ f64 │
#> ╞═════╪═════╪═════╡
#> │ b   ┆ 3.0 ┆ 2.0 │
#> └─────┴─────┴─────┘
#> 
#> [[4]]
#> shape: (1, 3)
#> ┌─────┬─────┬─────┐
#> │ a   ┆ b   ┆ c   │
#> │ --- ┆ --- ┆ --- │
#> │ str ┆ f64 ┆ f64 │
#> ╞═════╪═════╪═════╡
#> │ c   ┆ 3.0 ┆ 1.0 │
#> └─────┴─────┴─────┘