etiennebacher / tidypolars

Get the power of polars with the syntax of the tidyverse
https://tidypolars.etiennebacher.com
Other
172 stars 3 forks source link

Implement `by` and `.by` #59

Closed etiennebacher closed 10 months ago

etiennebacher commented 10 months ago

Close #28

library(dplyr, warn.conflicts = FALSE)
library(tidypolars)
#> Registered S3 method overwritten by 'tidypolars':
#>   method          from  
#>   print.DataFrame polars

iris |>
  as_polars() |> 
  filter(Sepal.Length == max(Sepal.Length), .by = Species)
#> shape: (3, 5)
#> ┌──────────────┬─────────────┬──────────────┬─────────────┬────────────┐
#> │ Sepal.Length ┆ Sepal.Width ┆ Petal.Length ┆ Petal.Width ┆ Species    │
#> │ ---          ┆ ---         ┆ ---          ┆ ---         ┆ ---        │
#> │ f64          ┆ f64         ┆ f64          ┆ f64         ┆ cat        │
#> ╞══════════════╪═════════════╪══════════════╪═════════════╪════════════╡
#> │ 5.8          ┆ 4.0         ┆ 1.2          ┆ 0.2         ┆ setosa     │
#> │ 7.0          ┆ 3.2         ┆ 4.7          ┆ 1.4         ┆ versicolor │
#> │ 7.9          ┆ 3.8         ┆ 6.4          ┆ 2.0         ┆ virginica  │
#> └──────────────┴─────────────┴──────────────┴─────────────┴────────────┘

mtcars |> 
  as_polars() |> 
  summarize(
    m_mpg = mean(mpg),
    sd_mpg = sd(mpg),
    .by = c(cyl, drat)
  )
#> shape: (26, 4)
#> ┌─────┬──────┬───────┬──────────┐
#> │ cyl ┆ drat ┆ m_mpg ┆ sd_mpg   │
#> │ --- ┆ ---  ┆ ---   ┆ ---      │
#> │ f64 ┆ f64  ┆ f64   ┆ f64      │
#> ╞═════╪══════╪═══════╪══════════╡
#> │ 6.0 ┆ 3.9  ┆ 21.0  ┆ 0.0      │
#> │ 4.0 ┆ 3.85 ┆ 22.8  ┆ null     │
#> │ 8.0 ┆ 3.07 ┆ 16.3  ┆ 1.053565 │
#> │ 8.0 ┆ 3.23 ┆ 14.7  ┆ null     │
#> │ …   ┆ …    ┆ …     ┆ …        │
#> │ 6.0 ┆ 3.92 ┆ 18.5  ┆ 0.989949 │
#> │ 4.0 ┆ 4.93 ┆ 30.4  ┆ null     │
#> │ 4.0 ┆ 3.7  ┆ 21.5  ┆ null     │
#> │ 6.0 ┆ 3.62 ┆ 19.7  ┆ null     │
#> └─────┴──────┴───────┴──────────┘