Convert categorical variables into dummy/indicator variables
Description
Convert categorical variables into dummy/indicator variables
Usage
<DataFrame>$to_dummies(
...,
separator = "_",
drop_first = FALSE,
drop_nulls = FALSE
)
Arguments
…
|
\<dynamic-dots \> Column names or selectors that should be
converted to dummy variables. If empty (default), convert all columns
(same as specifying with the selector cs$all() ).
|
separator
|
Separator/delimiter used when generating column names. |
drop_first
|
Remove the first category from the variables being encoded. |
drop_nulls
|
A boolean indicating whether to generate columns for null
values.
|
Value
A polars DataFrame
Examples
library("polars")
df <- pl$DataFrame(
foo = c(1L, 2L),
bar = c(3, NA),
ham = c("a", "b")
)
df$to_dummies()
#> shape: (2, 6)
#> ┌───────┬───────┬─────────┬──────────┬───────┬───────┐
#> │ foo_1 ┆ foo_2 ┆ bar_3.0 ┆ bar_null ┆ ham_a ┆ ham_b │
#> │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
#> │ u8 ┆ u8 ┆ u8 ┆ u8 ┆ u8 ┆ u8 │
#> ╞═══════╪═══════╪═════════╪══════════╪═══════╪═══════╡
#> │ 1 ┆ 0 ┆ 1 ┆ 0 ┆ 1 ┆ 0 │
#> │ 0 ┆ 1 ┆ 0 ┆ 1 ┆ 0 ┆ 1 │
#> └───────┴───────┴─────────┴──────────┴───────┴───────┘
#> shape: (2, 3)
#> ┌───────┬──────────┬───────┐
#> │ foo_2 ┆ bar_null ┆ ham_b │
#> │ --- ┆ --- ┆ --- │
#> │ u8 ┆ u8 ┆ u8 │
#> ╞═══════╪══════════╪═══════╡
#> │ 0 ┆ 0 ┆ 0 │
#> │ 1 ┆ 1 ┆ 1 │
#> └───────┴──────────┴───────┘
#> shape: (2, 5)
#> ┌───────┬───────┬─────────┬───────┬───────┐
#> │ foo_1 ┆ foo_2 ┆ bar_3.0 ┆ ham_a ┆ ham_b │
#> │ --- ┆ --- ┆ --- ┆ --- ┆ --- │
#> │ u8 ┆ u8 ┆ u8 ┆ u8 ┆ u8 │
#> ╞═══════╪═══════╪═════════╪═══════╪═══════╡
#> │ 1 ┆ 0 ┆ 1 ┆ 1 ┆ 0 │
#> │ 0 ┆ 1 ┆ 0 ┆ 0 ┆ 1 │
#> └───────┴───────┴─────────┴───────┴───────┘
#> shape: (2, 5)
#> ┌───────┬───────┬─────────┬──────────┬─────┐
#> │ foo:1 ┆ foo:2 ┆ bar:3.0 ┆ bar:null ┆ ham │
#> │ --- ┆ --- ┆ --- ┆ --- ┆ --- │
#> │ u8 ┆ u8 ┆ u8 ┆ u8 ┆ str │
#> ╞═══════╪═══════╪═════════╪══════════╪═════╡
#> │ 1 ┆ 0 ┆ 1 ┆ 0 ┆ a │
#> │ 0 ┆ 1 ┆ 0 ┆ 1 ┆ b │
#> └───────┴───────┴─────────┴──────────┴─────┘
#> shape: (2, 4)
#> ┌───────┬───────┬──────┬─────┐
#> │ foo:1 ┆ foo:2 ┆ bar ┆ ham │
#> │ --- ┆ --- ┆ --- ┆ --- │
#> │ u8 ┆ u8 ┆ f64 ┆ str │
#> ╞═══════╪═══════╪══════╪═════╡
#> │ 1 ┆ 0 ┆ 3.0 ┆ a │
#> │ 0 ┆ 1 ┆ null ┆ b │
#> └───────┴───────┴──────┴─────┘
#> shape: (2, 3)
#> ┌───────┬──────┬─────┐
#> │ foo:2 ┆ bar ┆ ham │
#> │ --- ┆ --- ┆ --- │
#> │ u8 ┆ f64 ┆ str │
#> ╞═══════╪══════╪═════╡
#> │ 0 ┆ 3.0 ┆ a │
#> │ 1 ┆ null ┆ b │
#> └───────┴──────┴─────┘