Convert to a Categorical or Enum data type
Description
Convert physical values to a Categorical or Enum data type. The input
must be of the physical type of the target data type,
i.e.
UInt32 for Categorical and UInt8,
UInt16 or UInt32 for Enum (depending on the
number of categories).
Usage
<Expr>$cat$to(dtype, ..., strict = TRUE)
Arguments
dtype
|
A Polars DataType or DataTypeExpr. Must be a Categorical or an Enum. |
…
|
These dots are for future extensions and must be empty. |
strict
|
If TRUE (default), raise an error if a value is not a valid
category. If FALSE, such values become null.
|
Value
A polars expression
See Also
-
\$cat$physical()
Examples
library("polars")
dtype <- pl$Enum(c("bar", "foo", "x"))
df <- pl$DataFrame(x = c(1, 0, 1, 2, NA))$cast(pl$UInt8)
df$with_columns(cat = pl$col("x")$cat$to(dtype))
#> shape: (5, 2)
#> ┌──────┬──────┐
#> │ x ┆ cat │
#> │ --- ┆ --- │
#> │ u8 ┆ enum │
#> ╞══════╪══════╡
#> │ 1 ┆ foo │
#> │ 0 ┆ bar │
#> │ 1 ┆ foo │
#> │ 2 ┆ x │
#> │ null ┆ null │
#> └──────┴──────┘
# Values that are not valid categories are converted to `null` when
# `strict = FALSE`
df2 <- pl$DataFrame(x = c(1, 0, 4))$cast(pl$UInt8)
df2$with_columns(cat = pl$col("x")$cat$to(dtype, strict = FALSE))
#> shape: (3, 2)
#> ┌─────┬──────┐
#> │ x ┆ cat │
#> │ --- ┆ --- │
#> │ u8 ┆ enum │
#> ╞═════╪══════╡
#> │ 1 ┆ foo │
#> │ 0 ┆ bar │
#> │ 4 ┆ null │
#> └─────┴──────┘