---
title: "Wide and long data formats"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
```

## Tidy data

Suppose we're interested in the influence of *Harry Potter*  on baby names.

```{r}
library(babynames)
b <- babynames %>% filter( ((name == "Harry") & (sex == "M")) | ((name == "Hermione") & (sex == "F")))   %>% 
  filter(year >= 1980) %>% 
  select(year, name, n)

b
```

The data frame `b` is in "tidy data" form: every row contains one measurement (the number of babies born, for a particular name and a particular year). This is also know as "long form."

So far in this class, pretty much all of our data was in "long form." It might be difficult to imagine how else we could store the data in `b` in a data frame.

Here is a way:

```{r}
wide <- b %>% pivot_wider(names_from = name, values_from = n)
wide
```

What we did is take the values in the column `n`, and distributed it across two columns: one column for each category in the column `b$name`.


We can go back to long form using `pivote_longer`:

```{r}
long <- wide %>% pivot_longer(cols = c(Harry, Hermione), names_to = "name", values_to = "n")
long
```


We created a new column `name`, and gathered values from the columns `Harry` and `Hermione` into one column `n`. You see some `NA`s there: that's because data for `Hermione` before 2000 is indeed missing (because `babynames` only has data for 5 births or more a year).

We can now display the data:

```{r message = "F", warning = "F"}
ggplot(long) + 
  geom_smooth(mapping = aes(x = year, y = n, color = name), method = "loess")
```

We can add 0's to the data if we like. `is.na(vec)` returns a vector of T's and F's, where T's correspond to `NA`s:

```{r}
a <- long$n
a[is.na(a)] <-  0
long$n <- a
```

Let's display this again:

```{r}
ggplot(long) + 
  geom_smooth(mapping = aes(x = year, y = n, color = name), method = "loess")
```

### Tidy data and `ggplot`

Note that `ggplot` doesn't work that well with wide tables: we could automatically display captions for the long table, but couldn't do that for the wide table, since we couldn't map color to `name` there.

