phplyr

Filter rows and add columns

Keep the penguins with a recorded body mass, and add the mass in kilograms and a size label to each. penguins has size measurements for 344 penguins near Palmer Station, Antarctica, from 2007 to 2009 (Gorman et al., 2014).

use Phibble\DataFrame;use function Phplyr\{filter, select, mutate, if_else, col};$data = 'https://raw.githubusercontent.com/phpstats'    . '/datasets/main/csv';$penguins = DataFrame::fromCsv("$data/penguins.csv");echo $penguins |>    filter(fn ($r) => $r->body_mass_g !== null) |>    select('species', 'island', 'sex', 'body_mass_g') |>    mutate(        mass_kg: fn ($r) => $r->body_mass_g / 1000,        size: if_else(            col('body_mass_g')->ge(4500),            'large',            'small',        ),    );
use Phibble\DataFrame;use function Phplyr\{phplyr, if_else, col};$data = 'https://raw.githubusercontent.com/phpstats'    . '/datasets/main/csv';$penguins = DataFrame::fromCsv("$data/penguins.csv");echo phplyr($penguins)    ->filter(fn ($r) => $r->body_mass_g !== null)    ->select('species', 'island', 'sex', 'body_mass_g')    ->mutate(        mass_kg: fn ($r) => $r->body_mass_g / 1000,        size: if_else(            col('body_mass_g')->ge(4500),            'large',            'small',        ),    );
# A tibble: 342 × 6
   species island    sex    body_mass_g mass_kg size 
   <chr>   <chr>     <chr>        <int>   <dbl> <chr>
 1 Adelie  Torgersen male          3750    3.75 small
 2 Adelie  Torgersen female        3800    3.8  small
 3 Adelie  Torgersen female        3250    3.25 small
 4 Adelie  Torgersen female        3450    3.45 small
 5 Adelie  Torgersen male          3650    3.65 small
 6 Adelie  Torgersen female        3625    3.62 small
 7 Adelie  Torgersen male          4675    4.68 large
 8 Adelie  Torgersen <NA>          3475    3.48 small
 9 Adelie  Torgersen <NA>          4250    4.25 small
10 Adelie  Torgersen <NA>          3300    3.3  small
# ℹ 332 more rows
  • filter() keeps the rows for which the row closure returns true. Two penguins have no recorded mass, so 342 rows remain.
  • select() keeps four columns, and mutate() adds one column for each named argument.
  • A row closure such as fn ($r) => $r->body_mass_g / 1000 runs once per row and reads the row’s columns as properties.
  • A column expression such as col('body_mass_g')->ge(4500) works on the whole column, and if_else() uses it to pick 'large' or 'small'.
  • sex is NA for some penguins. Missing values print as <NA>.

Reference: Single-table functions · Vector helpers