Skip to content

Cast between DataType

Source code

Description

Cast between DataType

Usage

<Expr>$cast(dtype, strict = TRUE)

Arguments

dtype DataType to cast to.
strict If TRUE (default), an error will be thrown if cast failed at resolve time.

Value

Expr

Examples

library(polars)

df = pl$DataFrame(a = 1:3, b = c(1, 2, 3))
df$with_columns(
  pl$col("a")$cast(pl$dtypes$Float64),
  pl$col("b")$cast(pl$dtypes$Int32)
)
#> shape: (3, 2)
#> ┌─────┬─────┐
#> │ a   ┆ b   │
#> │ --- ┆ --- │
#> │ f64 ┆ i32 │
#> ╞═════╪═════╡
#> │ 1.0 ┆ 1   │
#> │ 2.0 ┆ 2   │
#> │ 3.0 ┆ 3   │
#> └─────┴─────┘
# strict FALSE, inserts null for any cast failure
pl$lit(c(100, 200, 300))$cast(pl$dtypes$UInt8, strict = FALSE)$to_series()
#> polars Series: shape: (3,)
#> Series: '' [u8]
#> [
#>  100
#>  200
#>  null
#> ]
# strict TRUE, raise any failure as an error when query is executed.
tryCatch(
  {
    pl$lit("a")$cast(pl$dtypes$Float64, strict = TRUE)$to_series()
  },
  error = function(e) e
)
#> <RPolarsErr_error: Execution halted with the following contexts
#>    0: In R: in $select()
#>    0: During function call [.main()]
#>    1: Encountered the following error in Rust-Polars:
#>          conversion from `str` to `f64` failed in column 'literal' for 1 out of 1 values: ["a"]
#> >