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

# `nycflights23` dataset 

```{r}
#LOAD PACKAGES
library(tidyverse)

#LOAD DATA
library(nycflights23)
data("flights")
```


`nycflights23` contains information about all 435352 flights departing NYC in 2023. 

![](https://r4ds.hadley.nz/diagrams/relational.png)


# Join dataframes

## Matching key variable names

Some airline names might be easy to guess (ie. "UA" is United Airlines), but what airlines have the code "VX", "HA", and "B6"? Data on airline codes is provided in a dataset called `airlines`. 

```{r}
data("airlines")
```

We want to have all this information in one data frame instead of two separate data frames. 

The variable `carrier` in `flights` match the variable `carrier` in the `airlines` dataset -- this is our *key variable*. In this case, they have the same name, but this doesn't necessarily have to be true. 

```{r}

```


## Different key variable names

Say instead you are interested in the destinations of all domestic flights departing NYC in 2013, and you ask yourself questions like: “What cities are these airports in?”, or “Is "ORD" Orlando?”

```{r}
data("airports")
```


In `airports` the airport code is in `faa`, whereas in `flights` the airport codes are in `origin` and `dest`.

```{r}

```

Let’s construct the chain of pipe operators %>% that computes the number of flights from NYC to each destination, but also includes information about each destination airport:

```{r}

```

## Multiple Key variables

In order to join the flights and weather data frames, we need more than one key variable: `year`, `month`, `day`, `hour`, and `origin`. This is because the combination of these 5 variables act to uniquely identify each observational unit in the weather data frame: hourly weather recordings at each of the 3 NYC airports.

```{r}
data("weather")
```


```{r}

```

## Why is this useful? 

Updating labels: 

```{r}
flights %>% 
ggplot(aes(x = carrier, fill = origin)) +
  geom_bar() + 
  coord_flip()

#VS

flights %>% 
  inner_join(airports, by = c("origin" = "faa")) %>% 
  rename(origin_airport = name) %>% 
  inner_join(airlines, by = c("carrier")) %>%  
  rename(carrier_name= name) %>% 
ggplot(mapping = aes(x = carrier_name, fill = origin_airport)) +
  geom_bar() + 
  coord_flip()
```


Exploring relationships between variables in separate tables: 

```{r}
flights_weather_joined %>% 
  filter(dep_delay >0) %>% 
  ggplot(aes(x=temp, y=dep_delay)) +
  geom_point()
```

# Different Types of Joins

![Credit: RStudio](http://rafalab.dfci.harvard.edu/dsbook/wrangling/img/joins.png)

# Common Issues with Joining

- duplicate keys
- lowercase/uppercase
- symbols or whitespace
- Make sure the join fields are the same format.



