Fix code language
This commit is contained in:
		@@ -13,7 +13,7 @@ Introduction</h1>
 | 
			
		||||
Prerequisites</h2>
 | 
			
		||||
<p>In this chapter, we’ll explore the five related datasets from nycflights13 using the join functions from dplyr.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">library(tidyverse)
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">library(tidyverse)
 | 
			
		||||
library(nycflights13)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
</section>
 | 
			
		||||
@@ -31,7 +31,7 @@ Primary and foreign keys</h2>
 | 
			
		||||
<ul><li>
 | 
			
		||||
<p><code>airlines</code> records two pieces of data about each airline: its carrier code and its full name. You can identify an airline with its two letter carrier code, making <code>carrier</code> the primary key.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">airlines
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">airlines
 | 
			
		||||
#> # A tibble: 16 × 2
 | 
			
		||||
#>   carrier name                    
 | 
			
		||||
#>   <chr>   <chr>                   
 | 
			
		||||
@@ -47,7 +47,7 @@ Primary and foreign keys</h2>
 | 
			
		||||
<li>
 | 
			
		||||
<p><code>airports</code> records data about each airport. You can identify each airport by its three letter airport code, making <code>faa</code> the primary key.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">airports
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">airports
 | 
			
		||||
#> # A tibble: 1,458 × 8
 | 
			
		||||
#>   faa   name                             lat   lon   alt    tz dst   tzone   
 | 
			
		||||
#>   <chr> <chr>                          <dbl> <dbl> <dbl> <dbl> <chr> <chr>   
 | 
			
		||||
@@ -63,7 +63,7 @@ Primary and foreign keys</h2>
 | 
			
		||||
<li>
 | 
			
		||||
<p><code>planes</code> records data about each plane. You can identify a plane by its tail number, making <code>tailnum</code> the primary key.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">planes
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">planes
 | 
			
		||||
#> # A tibble: 3,322 × 9
 | 
			
		||||
#>   tailnum  year type                 manuf…¹ model engines seats speed engine
 | 
			
		||||
#>   <chr>   <int> <chr>                <chr>   <chr>   <int> <int> <int> <chr> 
 | 
			
		||||
@@ -79,7 +79,7 @@ Primary and foreign keys</h2>
 | 
			
		||||
<li>
 | 
			
		||||
<p><code>weather</code> records data about the weather at the origin airports. You can identify each observation by the combination of location and time, making <code>origin</code> and <code>time_hour</code> the compound primary key.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">weather
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">weather
 | 
			
		||||
#> # A tibble: 26,115 × 15
 | 
			
		||||
#>   origin  year month   day  hour  temp  dewp humid wind_dir wind_sp…¹ wind_…²
 | 
			
		||||
#>   <chr>  <int> <int> <int> <int> <dbl> <dbl> <dbl>    <dbl>     <dbl>   <dbl>
 | 
			
		||||
@@ -122,7 +122,7 @@ Primary and foreign keys</h2>
 | 
			
		||||
Checking primary keys</h2>
 | 
			
		||||
<p>Now that that we’ve identified the primary keys in each table, it’s good practice to verify that they do indeed uniquely identify each observation. One way to do that is to <code><a href="https://dplyr.tidyverse.org/reference/count.html">count()</a></code> the primary keys and look for entries where <code>n</code> is greater than one. This reveals that <code>planes</code> and <code>weather</code> both look good:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">planes |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">planes |> 
 | 
			
		||||
  count(tailnum) |> 
 | 
			
		||||
  filter(n > 1)
 | 
			
		||||
#> # A tibble: 0 × 2
 | 
			
		||||
@@ -136,7 +136,7 @@ weather |>
 | 
			
		||||
</div>
 | 
			
		||||
<p>You should also check for missing values in your primary keys — if a value is missing then it can’t identify an observation!</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">planes |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">planes |> 
 | 
			
		||||
  filter(is.na(tailnum))
 | 
			
		||||
#> # A tibble: 0 × 9
 | 
			
		||||
#> # … with 9 variables: tailnum <chr>, year <int>, type <chr>,
 | 
			
		||||
@@ -159,7 +159,7 @@ Surrogate keys</h2>
 | 
			
		||||
<p>So far we haven’t talked about the primary key for <code>flights</code>. It’s not super important here, because there are no data frames that use it as a foreign key, but it’s still useful to consider because it’s easier to work with observations if have some way to describe them to others.</p>
 | 
			
		||||
<p>After a little thinking and experimentation, we determined that there are three variables that together uniquely identify each flight:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights |> 
 | 
			
		||||
  count(time_hour, carrier, flight) |> 
 | 
			
		||||
  filter(n > 1)
 | 
			
		||||
#> # A tibble: 0 × 4
 | 
			
		||||
@@ -167,7 +167,7 @@ Surrogate keys</h2>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Does the absence of duplicates automatically make <code>time_hour</code>-<code>carrier</code>-<code>flight</code> a primary key? It’s certainly a good start, but it doesn’t guarantee it. For example, are altitude and latitude a good primary key for <code>airports</code>?</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">airports |>
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">airports |>
 | 
			
		||||
  count(alt, lat) |> 
 | 
			
		||||
  filter(n > 1)
 | 
			
		||||
#> # A tibble: 1 × 3
 | 
			
		||||
@@ -178,7 +178,7 @@ Surrogate keys</h2>
 | 
			
		||||
<p>Identifying an airport by it’s altitude and latitude is clearly a bad idea, and in general it’s not possible to know from the data alone whether or not a combination of variables makes a good a primary key. But for flights, the combination of <code>time_hour</code>, <code>carrier</code>, and <code>flight</code> seems reasonable because it would be really confusing for an airline and its customers if there were multiple flights with the same flight number in the air at the same time.</p>
 | 
			
		||||
<p>That said, we might be better off introducing a simple numeric surrogate key using the row number:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 <- flights |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 <- flights |> 
 | 
			
		||||
  mutate(id = row_number(), .before = 1)
 | 
			
		||||
flights2
 | 
			
		||||
#> # A tibble: 336,776 × 20
 | 
			
		||||
@@ -221,7 +221,7 @@ Basic joins</h1>
 | 
			
		||||
Mutating joins</h2>
 | 
			
		||||
<p>A <strong>mutating join</strong> allows you to combine variables from two data frames: it first matches observations by their keys, then copies across variables from one data frame to the other. Like <code><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>, the join functions add variables to the right, so if your dataset has many variables, you won’t see the new ones. For these examples, we’ll make it easier to see what’s going on by creating a narrower dataset with just six variables<span data-type="footnote">Remember that in RStudio you can also use <code><a href="https://rdrr.io/r/utils/View.html">View()</a></code> to avoid this problem.</span>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 <- flights |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 <- flights |> 
 | 
			
		||||
  select(year, time_hour, origin, dest, tailnum, carrier)
 | 
			
		||||
flights2
 | 
			
		||||
#> # A tibble: 336,776 × 6
 | 
			
		||||
@@ -237,7 +237,7 @@ flights2
 | 
			
		||||
</div>
 | 
			
		||||
<p>There are four types of mutating join, but there’s one that you’ll use almost all of the time: <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">left_join()</a></code>. It’s special because the output will always have the same rows as <code>x</code><span data-type="footnote">That’s not 100% true, but you’ll get a warning whenever it isn’t.</span>. The primary use of <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">left_join()</a></code> is to add in additional metadata. For example, we can use <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">left_join()</a></code> to add the full airline name to the <code>flights2</code> data:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 |>
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 |>
 | 
			
		||||
  left_join(airlines)
 | 
			
		||||
#> Joining with `by = join_by(carrier)`
 | 
			
		||||
#> # A tibble: 336,776 × 7
 | 
			
		||||
@@ -253,7 +253,7 @@ flights2
 | 
			
		||||
</div>
 | 
			
		||||
<p>Or we could find out the temperature and wind speed when each plane departed:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 |> 
 | 
			
		||||
  left_join(weather |> select(origin, time_hour, temp, wind_speed))
 | 
			
		||||
#> Joining with `by = join_by(time_hour, origin)`
 | 
			
		||||
#> # A tibble: 336,776 × 8
 | 
			
		||||
@@ -269,7 +269,7 @@ flights2
 | 
			
		||||
</div>
 | 
			
		||||
<p>Or what size of plane was flying:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 |> 
 | 
			
		||||
  left_join(planes |> select(tailnum, type, engines, seats))
 | 
			
		||||
#> Joining with `by = join_by(tailnum)`
 | 
			
		||||
#> # A tibble: 336,776 × 9
 | 
			
		||||
@@ -285,7 +285,7 @@ flights2
 | 
			
		||||
</div>
 | 
			
		||||
<p>When <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">left_join()</a></code> fails to find a match for a row in <code>x</code>, it fills in the new variables with missing values. For example, there’s no information about the plane with tail number <code>N3ALAA</code> so the <code>type</code>, <code>engines</code>, and <code>seats</code> will be missing:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 |> 
 | 
			
		||||
  filter(tailnum == "N3ALAA") |> 
 | 
			
		||||
  left_join(planes |> select(tailnum, type, engines, seats))
 | 
			
		||||
#> Joining with `by = join_by(tailnum)`
 | 
			
		||||
@@ -308,7 +308,7 @@ flights2
 | 
			
		||||
Specifying join keys</h2>
 | 
			
		||||
<p>By default, <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">left_join()</a></code> will use all variables that appear in both data frames as the join key, the so called <strong>natural</strong> join. This is a useful heuristic, but it doesn’t always work. For example, what happens if we try to join <code>flights2</code> with the complete <code>planes</code> dataset?</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 |> 
 | 
			
		||||
  left_join(planes)
 | 
			
		||||
#> Joining with `by = join_by(year, tailnum)`
 | 
			
		||||
#> # A tibble: 336,776 × 13
 | 
			
		||||
@@ -325,7 +325,7 @@ Specifying join keys</h2>
 | 
			
		||||
</div>
 | 
			
		||||
<p>We get a lot of missing matches because our join is trying to use <code>tailnum</code> and <code>year</code> as a compound key. Both <code>flights</code> and <code>planes</code> have a <code>year</code> column but they mean different things: <code>flights$year</code> is year the flight occurred and <code>planes$year</code> is the year the plane was built. We only want to join on <code>tailnum</code> so we need to provide an explicit specification with <code><a href="https://dplyr.tidyverse.org/reference/join_by.html">join_by()</a></code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 |> 
 | 
			
		||||
  left_join(planes, join_by(tailnum))
 | 
			
		||||
#> # A tibble: 336,776 × 14
 | 
			
		||||
#>   year.x time_hour           origin dest  tailnum carrier year.y type        
 | 
			
		||||
@@ -343,7 +343,7 @@ Specifying join keys</h2>
 | 
			
		||||
<p><code>join_by(tailnum)</code> is short for <code>join_by(tailnum == tailnum)</code>. It’s important to know about this fuller form for two reasons. Firstly, it describes the relationship between the two tables: the keys must be equal. That’s why this type of join is often called an <strong>equi-join</strong>. You’ll learn about non-equi-joins in <a href="#sec-non-equi-joins" data-type="xref">#sec-non-equi-joins</a>.</p>
 | 
			
		||||
<p>Secondly, it’s how you specify different join keys in each table. For example, there are two ways to join the <code>flight2</code> and <code>airports</code> table: either by <code>dest</code> or <code>origin:</code></p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 |> 
 | 
			
		||||
  left_join(airports, join_by(dest == faa))
 | 
			
		||||
#> # A tibble: 336,776 × 13
 | 
			
		||||
#>    year time_hour           origin dest  tailnum carrier name       lat   lon
 | 
			
		||||
@@ -384,7 +384,7 @@ flights2 |>
 | 
			
		||||
Filtering joins</h2>
 | 
			
		||||
<p>As you might guess the primary action of a <strong>filtering join</strong> is to filter the rows. There are two types: semi-joins and anti-joins. <strong>Semi-joins</strong> keep all rows in <code>x</code> that have a match in <code>y</code>. For example, we could use a semi-join to filter the <code>airports</code> dataset to show just the origin airports:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">airports |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">airports |> 
 | 
			
		||||
  semi_join(flights2, join_by(faa == origin))
 | 
			
		||||
#> # A tibble: 3 × 8
 | 
			
		||||
#>   faa   name                  lat   lon   alt    tz dst   tzone           
 | 
			
		||||
@@ -395,7 +395,7 @@ Filtering joins</h2>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Or just the destinations:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">airports |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">airports |> 
 | 
			
		||||
  semi_join(flights2, join_by(faa == dest))
 | 
			
		||||
#> # A tibble: 101 × 8
 | 
			
		||||
#>   faa   name                               lat    lon   alt    tz dst   tzone
 | 
			
		||||
@@ -410,7 +410,7 @@ Filtering joins</h2>
 | 
			
		||||
</div>
 | 
			
		||||
<p><strong>Anti-joins</strong> are the opposite: they return all rows in <code>x</code> that don’t have a match in <code>y</code>. They’re useful for finding missing values that are <strong>implicit</strong> in the data, the topic of <a href="#sec-missing-implicit" data-type="xref">#sec-missing-implicit</a>. Implicitly missing values don’t show up as <code>NA</code>s but instead only exist as an absence. For example, we can find rows that as missing from <code>airports</code> by looking for flights that don’t have a matching destination airport:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 |> 
 | 
			
		||||
  anti_join(airports, join_by(dest == faa)) |> 
 | 
			
		||||
  distinct(dest)
 | 
			
		||||
#> # A tibble: 4 × 1
 | 
			
		||||
@@ -423,7 +423,7 @@ Filtering joins</h2>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Or we can find which <code>tailnum</code>s are missing from <code>planes</code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 |>
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 |>
 | 
			
		||||
  anti_join(planes, join_by(tailnum)) |> 
 | 
			
		||||
  distinct(tailnum)
 | 
			
		||||
#> # A tibble: 722 × 1
 | 
			
		||||
@@ -446,7 +446,7 @@ Exercises</h2>
 | 
			
		||||
<li>
 | 
			
		||||
<p>Imagine you’ve found the top 10 most popular destinations using this code:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">top_dest <- flights2 |>
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">top_dest <- flights2 |>
 | 
			
		||||
  count(dest, sort = TRUE) |>
 | 
			
		||||
  head(10)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
@@ -459,7 +459,7 @@ Exercises</h2>
 | 
			
		||||
<li>
 | 
			
		||||
<p>Compute the average delay by destination, then join on the <code>airports</code> data frame so you can show the spatial distribution of delays. Here’s an easy way to draw a map of the United States:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">airports |>
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">airports |>
 | 
			
		||||
  semi_join(flights, join_by(faa == dest)) |>
 | 
			
		||||
  ggplot(aes(lon, lat)) +
 | 
			
		||||
    borders("state") +
 | 
			
		||||
@@ -477,7 +477,7 @@ Exercises</h2>
 | 
			
		||||
How do joins work?</h1>
 | 
			
		||||
<p>Now that you’ve used joins a few times it’s time to learn more about how they work, focusing on how each row in <code>x</code> matches rows in <code>y</code>. We’ll begin by using <a href="#fig-join-setup" data-type="xref">#fig-join-setup</a> to introduce a visual representation of the two simple tibbles defined below. In these examples we’ll use a single key called <code>key</code> and a single value column (<code>val_x</code> and <code>val_y</code>), but the ideas all generalize to multiple keys and multiple values.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">x <- tribble(
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">x <- tribble(
 | 
			
		||||
  ~key, ~val_x,
 | 
			
		||||
     1, "x1",
 | 
			
		||||
     2, "x2",
 | 
			
		||||
@@ -583,7 +583,7 @@ Row matching</h2>
 | 
			
		||||
<li>There might be the same number of rows if some rows don’t match any rows, and exactly the same number of rows match two rows in <code>y</code>!!</li>
 | 
			
		||||
</ul><p>Row expansion is a fundamental property of joins, but it’s dangerous because it might happen without you realizing it. To avoid this problem, dplyr will warn whenever there are multiple matches:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df1 <- tibble(key = c(1, 2, 3), val_x = c("x1", "x2", "x3"))
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">df1 <- tibble(key = c(1, 2, 3), val_x = c("x1", "x2", "x3"))
 | 
			
		||||
df2 <- tibble(key = c(1, 2, 2), val_y = c("y1", "y2", "y3"))
 | 
			
		||||
 | 
			
		||||
df1 |> 
 | 
			
		||||
@@ -613,7 +613,7 @@ df1 |>
 | 
			
		||||
One-to-one mapping</h2>
 | 
			
		||||
<p>Both <code>unmatched</code> and <code>multiple</code> can take value <code>"error"</code> which means that the join will fail unless each row in <code>x</code> matches exactly one row in <code>y</code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df1 <- tibble(x = 1)
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">df1 <- tibble(x = 1)
 | 
			
		||||
df2 <- tibble(x = c(1, 1))
 | 
			
		||||
df3 <- tibble(x = 3)
 | 
			
		||||
 | 
			
		||||
@@ -636,12 +636,12 @@ df1 |>
 | 
			
		||||
Allow multiple rows</h2>
 | 
			
		||||
<p>Sometimes it’s useful to deliberately expand the number of rows in the output. This can come about naturally if you “flip” the direction of the question you’re asking. For example, as we’ve seen above, it’s natural to supplement the <code>flights</code> data with information about the plane that flew each flight:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">flights2 |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">flights2 |> 
 | 
			
		||||
  left_join(planes, by = "tailnum")</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>But it’s also reasonable to ask what flights did each plane fly:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">plane_flights <- planes |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">plane_flights <- planes |> 
 | 
			
		||||
  select(tailnum, type, engines, seats) |> 
 | 
			
		||||
  left_join(flights2, by = "tailnum")
 | 
			
		||||
#> Warning in left_join(select(planes, tailnum, type, engines, seats), flights2, : Each row in `x` is expected to match at most 1 row in `y`.
 | 
			
		||||
@@ -651,7 +651,7 @@ Allow multiple rows</h2>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Since this duplicates rows in <code>x</code> (the planes), we need to explicitly say that we’re ok with the multiple matches by setting <code>multiple = "all"</code>:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">plane_flights <- planes |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">plane_flights <- planes |> 
 | 
			
		||||
  select(tailnum, type, engines, seats) |> 
 | 
			
		||||
  left_join(flights2, by = "tailnum", multiple = "all")
 | 
			
		||||
 | 
			
		||||
@@ -698,7 +698,7 @@ Non-equi joins</h1>
 | 
			
		||||
<p>So far you’ve only seen equi-joins, joins where the rows match if the <code>x</code> key equals the <code>y</code> key. Now we’re going to relax that restriction and discuss other ways of determining if a pair of rows match.</p>
 | 
			
		||||
<p>But before we can do that, we need to revisit a simplification we made above. In equi-joins the <code>x</code> keys and <code>y</code> are always equal, so we only need to show one in the output. We can request that dplyr keep both keys with <code>keep = TRUE</code>, leading to the code below and the re-drawn <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">inner_join()</a></code> in <a href="#fig-inner-both" data-type="xref">#fig-inner-both</a>.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">x |> left_join(y, by = "key", keep = TRUE)
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">x |> left_join(y, by = "key", keep = TRUE)
 | 
			
		||||
#> # A tibble: 3 × 4
 | 
			
		||||
#>   key.x val_x key.y val_y
 | 
			
		||||
#>   <dbl> <chr> <dbl> <chr>
 | 
			
		||||
@@ -748,7 +748,7 @@ Cross joins</h2>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Cross joins are useful when generating permutations. For example, the code below generates every possible pair of names. Since we’re joining <code>df</code> to itself, this is sometimes called a <strong>self-join</strong>.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df <- tibble(name = c("John", "Simon", "Tracy", "Max"))
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">df <- tibble(name = c("John", "Simon", "Tracy", "Max"))
 | 
			
		||||
df |> left_join(df, join_by())
 | 
			
		||||
#> # A tibble: 16 × 2
 | 
			
		||||
#>   name.x name.y
 | 
			
		||||
@@ -777,7 +777,7 @@ Inequality joins</h2>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Inequality joins are extremely general, so general that it’s hard to come up with meaningful specific use cases. One small useful technique is to use them to restrict the cross join so that instead of generating all permutations, we generate all combinations:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">df <- tibble(id = 1:4, name = c("John", "Simon", "Tracy", "Max"))
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">df <- tibble(id = 1:4, name = c("John", "Simon", "Tracy", "Max"))
 | 
			
		||||
 | 
			
		||||
df |> left_join(df, join_by(id < id))
 | 
			
		||||
#> # A tibble: 7 × 4
 | 
			
		||||
@@ -808,14 +808,14 @@ Rolling joins</h2>
 | 
			
		||||
<p>Rolling joins are particularly useful when you have two tables of dates that don’t perfectly line up and you want to find (e.g.) the closest date in table 1 that comes before (or after) some date in table 2.</p>
 | 
			
		||||
<p>For example, imagine that you’re in charge of the party planning commission for your office. Your company is rather cheap so instead of having individual parties, you only have a party once each quarter. The rules for determining when a party will be held are a little complex: parties are always on a Monday, you skip the first week of January since a lot of people are on holiday, and the first Monday of Q3 2022 is July 4, so that has to be pushed back a week. That leads to the following party days:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">parties <- tibble(
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">parties <- tibble(
 | 
			
		||||
  q = 1:4,
 | 
			
		||||
  party = lubridate::ymd(c("2022-01-10", "2022-04-04", "2022-07-11", "2022-10-03"))
 | 
			
		||||
)</pre>
 | 
			
		||||
</div>
 | 
			
		||||
<p>Now imagine that you have a table of employee birthdays:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">employees <- tibble(
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">employees <- tibble(
 | 
			
		||||
  name = wakefield::name(100),
 | 
			
		||||
  birthday = lubridate::ymd("2022-01-01") + (sample(365, 100, replace = TRUE) - 1)
 | 
			
		||||
)
 | 
			
		||||
@@ -833,7 +833,7 @@ employees
 | 
			
		||||
</div>
 | 
			
		||||
<p>And for each employee we want to find the first party date that comes after (or on) their birthday. We can express that with a rolling join:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">employees |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">employees |> 
 | 
			
		||||
  left_join(parties, join_by(closest(birthday >= party)))
 | 
			
		||||
#> # A tibble: 100 × 4
 | 
			
		||||
#>   name       birthday       q party     
 | 
			
		||||
@@ -848,7 +848,7 @@ employees
 | 
			
		||||
</div>
 | 
			
		||||
<p>There is, however, one problem with this approach: the folks with birthdays before January 10 don’t get a party:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">employees |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">employees |> 
 | 
			
		||||
  anti_join(parties, join_by(closest(birthday >= party)))
 | 
			
		||||
#> # A tibble: 4 × 2
 | 
			
		||||
#>   name       birthday  
 | 
			
		||||
@@ -873,7 +873,7 @@ Overlap joins</h2>
 | 
			
		||||
<code>overlaps(x_lower, x_upper, y_lower, y_upper)</code> is short for <code>x_lower <= y_upper, x_upper >= y_lower</code>.</li>
 | 
			
		||||
</ul><p>Let’s continue the birthday example to see how you might use them. There’s one problem with the strategy we used above: there’s no party preceding the birthdays Jan 1-9. So it might be better to to be explicit about the date ranges that each party spans, and make a special case for those early birthdays:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">parties <- tibble(
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">parties <- tibble(
 | 
			
		||||
  q = 1:4,
 | 
			
		||||
  party = lubridate::ymd(c("2022-01-10", "2022-04-04", "2022-07-11", "2022-10-03")),
 | 
			
		||||
  start = lubridate::ymd(c("2022-01-01", "2022-04-04", "2022-07-11", "2022-10-03")),
 | 
			
		||||
@@ -890,7 +890,7 @@ parties
 | 
			
		||||
</div>
 | 
			
		||||
<p>Hadley is hopelessly bad at data entry so he also wanted to check that the party periods don’t overlap. One way to do this is by using a self-join to check to if any start-end interval overlap with another:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">parties |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">parties |> 
 | 
			
		||||
  inner_join(parties, join_by(overlaps(start, end, start, end), q < q)) |> 
 | 
			
		||||
  select(start.x, end.x, start.y, end.y)
 | 
			
		||||
#> # A tibble: 1 × 4
 | 
			
		||||
@@ -900,7 +900,7 @@ parties
 | 
			
		||||
</div>
 | 
			
		||||
<p>Ooops, there is an overlap, so let’s fix that problem and continue:</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">parties <- tibble(
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">parties <- tibble(
 | 
			
		||||
  q = 1:4,
 | 
			
		||||
  party = lubridate::ymd(c("2022-01-10", "2022-04-04", "2022-07-11", "2022-10-03")),
 | 
			
		||||
  start = lubridate::ymd(c("2022-01-01", "2022-04-04", "2022-07-11", "2022-10-03")),
 | 
			
		||||
@@ -909,7 +909,7 @@ parties
 | 
			
		||||
</div>
 | 
			
		||||
<p>Now we can match each employee to their party. This is a good place to use <code>unmatched = "error"</code> because we want to quickly find out if any employees didn’t get assigned a party.</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">employees |> 
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">employees |> 
 | 
			
		||||
  inner_join(parties, join_by(between(birthday, start, end)), unmatched = "error")
 | 
			
		||||
#> # A tibble: 100 × 6
 | 
			
		||||
#>   name       birthday       q party      start      end       
 | 
			
		||||
@@ -930,7 +930,7 @@ Exercises</h2>
 | 
			
		||||
<ol type="1"><li>
 | 
			
		||||
<p>Can you explain what’s happening with the keys in this equi-join? Why are they different?</p>
 | 
			
		||||
<div class="cell">
 | 
			
		||||
<pre data-type="programlisting" data-code-language="downlit">x |> full_join(y, by = "key")
 | 
			
		||||
<pre data-type="programlisting" data-code-language="r">x |> full_join(y, by = "key")
 | 
			
		||||
#> # A tibble: 4 × 3
 | 
			
		||||
#>     key val_x val_y
 | 
			
		||||
#>   <dbl> <chr> <chr>
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user