---
title: "Operations on data tables"
toc-title: "group_by()"
toc: true
theme: darkly
format:
  html: 
    code-overflow: wrap
    toc: true
    toc-title: "Table of Contents"
    code-fold: true
include-in-header:
  - text: |
      <style>
      .cell-output-stdout code {
        word-break: break-wor !important;
        white-space: pre-wrap !important;
      }
      </style>
execute:
  warning: false
  message: false
---

Creating a summary is an example of an operation on a table.  Joining two tables together is as well. Creating summaries of groups of data is also discussed here.    

# Table Operations

## [bind_rows](https://dplyr.tidyverse.org/reference/bind_rows.html)

Glue two tables together using `bind_rows`.  Experiment to learn how different variables are handled.

## [group_by()](https://r4ds.hadley.nz/data-transform#groups)

Shuffle a dataset into groups, so that subsequent analysis is done "by group" using `group_by()`.

```{r eval = FALSE, echo = FALSE}
flights |> group_by(year,month,day) |> summarize(mx = max(arr_delay,na.rm=TRUE)) |> arrange((mx)) |> print(n=30) 
```

### [summarize()](https://r4ds.hadley.nz/data-transform#sec-summarize)

`Summarize()` transforms your data table into one or more rows, where each row constitutes a summary of the corresponding data.

1. Find the max of a single variable.
```{r}
library(tidyverse)
library(palmerpenguins)
penguins |> summarize(mx_bd = max(bill_depth_mm)) 
```

2. Find the max of single variable *within each group*.
```{r}
penguins |> group_by(species) |>
  summarize(mx_bd = max(bill_depth_mm, na.rm = TRUE))
```
3. Improve your summary with `n = n()`
```{r}
penguins |> group_by(species) |>
  summarize(mx_bd = max(bill_depth_mm, na.rm = TRUE), n = n())
```

4.  Exercise:  What's wrong with this code?
```{r}
penguins |> group_by(species) |>
  summarize(mx_bd = max(bill_depth_mm, na.rm = TRUE, n = n()))
```

5. Find the number of observations (rows) within each group. 
```{r}
penguins |> group_by(species) |> summarize(n = n())
```

## The [slice_](https://r4ds.hadley.nz/data-transform#the-slice_-functions) functions

1. `df |> slice_head(n = 1)` takes the first row from each group.
2. `df |> slice_tail(n = 1)` takes the last row in each group.
3. `df |> slice_min(x, n = 1)` takes the row with the smallest value of column x.
4. `df |> slice_max(x, n = 1)` takes the row with the largest value of column x.
5. `df |> slice_sample(n = 1)` takes one random row.

## Ungrouping & [`.by()`](https://r4ds.hadley.nz/data-transform#by)

To remove grouping use `ungroup()`, and to do "in-line" grouping on a per-operation basis you can use `.by()`

```{r}
penguins |> summarize(
  mx_bd = max(bill_depth_mm), 
  n = n(), 
  .by = species)
```

