Skip to content

Registering custom functionality with a polars Series

Description

Registering custom functionality with a polars Series

Usage

pl_api_register_series_namespace(name, ns_fn)

Arguments

name Name under which the functionality will be accessed.
ns_fn A function returns a new environment with the custom functionality. See examples for details.

Value

NULL invisibly.

Examples

library("polars")

# s: polars series
math_shortcuts <- function(s) {
  # Create a new environment to store the methods
  self <- new.env(parent = emptyenv())

  # Store the series
  self$`_s` <- s

  # Add methods
  self$square <- function() self$`_s` * self$`_s`
  self$cube <- function() self$`_s` * self$`_s` * self$`_s`

  # Set the class
  class(self) <- c("polars_namespace_series", "polars_object")

  # Return the environment
  self
}

pl$api$register_series_namespace("math", math_shortcuts)

s <- as_polars_series(c(1.5, 31, 42, 64.5))
s$math$square()$rename("s^2")
#> shape: (4,)
#> Series: 's^2' [f64]
#> [
#>  2.25
#>  961.0
#>  1764.0
#>  4160.25
#> ]
s <- as_polars_series(1:5)
s$math$cube()$rename("s^3")
#> shape: (5,)
#> Series: 's^3' [i32]
#> [
#>  1
#>  8
#>  27
#>  64
#>  125
#> ]