Skip to content

Cast DataFrame column(s) to the specified dtype

Source code

Description

This allows to convert all columns to a datatype or to convert only specific columns. Contrarily to the Python implementation, it is not possible to convert all columns of a specific datatype to another datatype.

Usage

<DataFrame>$cast(dtypes, ..., strict = TRUE)

Arguments

dtypes Either a datatype or a list where the names are column names and the values are the datatypes to convert to.
Ignored.
strict If TRUE (default), throw an error if a cast could not be done (for instance, due to an overflow). Otherwise, return null.

Value

A DataFrame

Examples

library("polars")

df = pl$DataFrame(
  foo = 1:3,
  bar = c(6, 7, 8),
  ham = as.Date(c("2020-01-02", "2020-03-04", "2020-05-06"))
)

# Cast only some columns
df$cast(list(foo = pl$Float32, bar = pl$UInt8))
#> shape: (3, 3)
#> ┌─────┬─────┬────────────┐
#> │ foo ┆ bar ┆ ham        │
#> │ --- ┆ --- ┆ ---        │
#> │ f32 ┆ u8  ┆ date       │
#> ╞═════╪═════╪════════════╡
#> │ 1.0 ┆ 6   ┆ 2020-01-02 │
#> │ 2.0 ┆ 7   ┆ 2020-03-04 │
#> │ 3.0 ┆ 8   ┆ 2020-05-06 │
#> └─────┴─────┴────────────┘
# Cast all columns to the same type
df$cast(pl$String)
#> shape: (3, 3)
#> ┌─────┬─────┬────────────┐
#> │ foo ┆ bar ┆ ham        │
#> │ --- ┆ --- ┆ ---        │
#> │ str ┆ str ┆ str        │
#> ╞═════╪═════╪════════════╡
#> │ 1   ┆ 6.0 ┆ 2020-01-02 │
#> │ 2   ┆ 7.0 ┆ 2020-03-04 │
#> │ 3   ┆ 8.0 ┆ 2020-05-06 │
#> └─────┴─────┴────────────┘