ddotta / cookbook-rpolars

Cookbook to provide solutions to common tasks and problems in using Polars with R
https://ddotta.github.io/cookbook-rpolars/
Creative Commons Attribution 4.0 International
57 stars 13 forks source link

Start a new section about using functions with polars #21

Closed ddotta closed 1 year ago

ddotta commented 1 year ago

An example that works:

fn_transformation <- function(data) {

  data$
    # Convert Categorical columns into Strings 
    with_columns(
      pl$col(pl$Categorical)$cast(pl$Utf8))$
    # Make all Strings columns uppercase
    with_columns(
      pl$col(pl$Utf8)$str$to_uppercase())$
    # Filter only the third first rows
    head(3)

}

fn_transformation(pl$DataFrame(iris))

shape: (3, 5)
┌──────────────┬─────────────┬──────────────┬─────────────┬─────────┐
│ Sepal.Length ┆ Sepal.Width ┆ Petal.Length ┆ Petal.Width ┆ Species │
│ ---          ┆ ---         ┆ ---          ┆ ---         ┆ ---     │
│ f64          ┆ f64         ┆ f64          ┆ f64         ┆ str     │
╞══════════════╪═════════════╪══════════════╪═════════════╪═════════╡
│ 5.1          ┆ 3.5         ┆ 1.4          ┆ 0.2         ┆ SETOSA  │
│ 4.9          ┆ 3.0         ┆ 1.4          ┆ 0.2         ┆ SETOSA  │
│ 4.7          ┆ 3.2         ┆ 1.3          ┆ 0.2         ┆ SETOSA  │
└──────────────┴─────────────┴──────────────┴─────────────┴─────────┘