973 lines
69 KiB
HTML
973 lines
69 KiB
HTML
<section data-type="chapter" id="chp-joins">
|
||
<h1><span id="sec-joins" class="quarto-section-identifier d-none d-lg-block"><span class="chapter-title">Joins</span></span></h1><div data-type="note"><div class="callout-body d-flex">
|
||
<div class="callout-icon-container">
|
||
<i class="callout-icon"/>
|
||
</div>
|
||
|
||
</div>
|
||
|
||
<p>You are reading the work-in-progress second edition of R for Data Science. This chapter should be readable but is currently undergoing final polishing. You can find the complete first edition at <a href="https://r4ds.had.co.nz" class="uri">https://r4ds.had.co.nz</a>.</p></div>
|
||
|
||
<section id="introduction" data-type="sect1">
|
||
<h1>
|
||
Introduction</h1>
|
||
<p>It’s rare that a data analysis involves only a single data frame. Typically you have many data frames, and you must <strong>join</strong> them together to answer the questions that you’re interested in. This chapter will introduce you to two important types of joins:</p>
|
||
<ul><li>Mutating joins, which add new variables to one data frame from matching observations in another.</li>
|
||
<li>Filtering joins, which filter observations from one data frame based on whether or not they match an observation in another.</li>
|
||
</ul><p>We’ll begin by discussing keys, the variables used to connect a pair of data frames in a join. We cement the theory with an examination of the keys in the nycflights13 datasets, then use that knowledge to start joining data frames together. Next we’ll discuss how joins work, focusing on their action on the rows. We’ll finish up with a discussion of non-equi-joins, a family of joins that provide a more flexible way of matching keys than the default equality relationship.</p>
|
||
|
||
<section id="prerequisites" data-type="sect2">
|
||
<h2>
|
||
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)
|
||
library(nycflights13)</pre>
|
||
</div>
|
||
</section>
|
||
</section>
|
||
|
||
<section id="keys" data-type="sect1">
|
||
<h1>
|
||
Keys</h1>
|
||
<p>To understand joins, you need to first understand how two tables can be connected through a pair of keys, with on each table. In this section, you’ll learn about the two types of key and see examples of both in the datasets of the nycflights13 package. You’ll also learn how to check that your keys are valid, and what to do if your table lacks a key.</p>
|
||
|
||
<section id="primary-and-foreign-keys" data-type="sect2">
|
||
<h2>
|
||
Primary and foreign keys</h2>
|
||
<p>Every join involves a pair of keys: a primary key and a foreign key. A <strong>primary key</strong> is a variable or set of variables that uniquely identifies each observation. When more than one variable is needed, the key is called a <strong>compound key.</strong> For example, in nycfights13:</p>
|
||
<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
|
||
#> # A tibble: 16 × 2
|
||
#> carrier name
|
||
#> <chr> <chr>
|
||
#> 1 9E Endeavor Air Inc.
|
||
#> 2 AA American Airlines Inc.
|
||
#> 3 AS Alaska Airlines Inc.
|
||
#> 4 B6 JetBlue Airways
|
||
#> 5 DL Delta Air Lines Inc.
|
||
#> 6 EV ExpressJet Airlines Inc.
|
||
#> # … with 10 more rows</pre>
|
||
</div>
|
||
</li>
|
||
<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
|
||
#> # A tibble: 1,458 × 8
|
||
#> faa name lat lon alt tz dst tzone
|
||
#> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <chr> <chr>
|
||
#> 1 04G Lansdowne Airport 41.1 -80.6 1044 -5 A America/Ne…
|
||
#> 2 06A Moton Field Municipal Airport 32.5 -85.7 264 -6 A America/Ch…
|
||
#> 3 06C Schaumburg Regional 42.0 -88.1 801 -6 A America/Ch…
|
||
#> 4 06N Randall Airport 41.4 -74.4 523 -5 A America/Ne…
|
||
#> 5 09J Jekyll Island Airport 31.1 -81.4 11 -5 A America/Ne…
|
||
#> 6 0A9 Elizabethton Municipal Airport 36.4 -82.2 1593 -5 A America/Ne…
|
||
#> # … with 1,452 more rows</pre>
|
||
</div>
|
||
</li>
|
||
<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
|
||
#> # A tibble: 3,322 × 9
|
||
#> tailnum year type manuf…¹ model engines seats speed engine
|
||
#> <chr> <int> <chr> <chr> <chr> <int> <int> <int> <chr>
|
||
#> 1 N10156 2004 Fixed wing multi engine EMBRAER EMB-… 2 55 NA Turbo…
|
||
#> 2 N102UW 1998 Fixed wing multi engine AIRBUS… A320… 2 182 NA Turbo…
|
||
#> 3 N103US 1999 Fixed wing multi engine AIRBUS… A320… 2 182 NA Turbo…
|
||
#> 4 N104UW 1999 Fixed wing multi engine AIRBUS… A320… 2 182 NA Turbo…
|
||
#> 5 N10575 2002 Fixed wing multi engine EMBRAER EMB-… 2 55 NA Turbo…
|
||
#> 6 N105UW 1999 Fixed wing multi engine AIRBUS… A320… 2 182 NA Turbo…
|
||
#> # … with 3,316 more rows, and abbreviated variable name ¹manufacturer</pre>
|
||
</div>
|
||
</li>
|
||
<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
|
||
#> # A tibble: 26,115 × 15
|
||
#> origin year month day hour temp dewp humid wind_dir wind_speed wind_gust
|
||
#> <chr> <int> <int> <int> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
|
||
#> 1 EWR 2013 1 1 1 39.0 26.1 59.4 270 10.4 NA
|
||
#> 2 EWR 2013 1 1 2 39.0 27.0 61.6 250 8.06 NA
|
||
#> 3 EWR 2013 1 1 3 39.0 28.0 64.4 240 11.5 NA
|
||
#> 4 EWR 2013 1 1 4 39.9 28.0 62.2 250 12.7 NA
|
||
#> 5 EWR 2013 1 1 5 39.0 28.0 64.4 260 12.7 NA
|
||
#> 6 EWR 2013 1 1 6 37.9 28.0 67.2 240 11.5 NA
|
||
#> # … with 26,109 more rows, and 4 more variables: precip <dbl>, pressure <dbl>,
|
||
#> # visib <dbl>, time_hour <dttm></pre>
|
||
</div>
|
||
</li>
|
||
</ul><p>A <strong>foreign key</strong> is a variable (or set of variables) that corresponds to a primary key in another table. For example:</p>
|
||
<ul><li>
|
||
<code>flights$tailnum</code> is a foreign key that corresponds to the primary key <code>planes$tailnum</code>.</li>
|
||
<li>
|
||
<code>flights$carrier</code> is a foreign key that corresponds to the primary key <code>airlines$carrier</code>.</li>
|
||
<li>
|
||
<code>flights$origin</code> is a foreign key that corresponds to the primary key <code>airports$faa</code>.</li>
|
||
<li>
|
||
<code>flights$dest</code> is a foreign key that corresponds to the primary key <code>airports$faa</code> .</li>
|
||
<li>
|
||
<code>flights$origin</code>-<code>flights$time_hour</code> is a compound foreign key that corresponds to the compound primary key <code>weather$origin</code>-<code>weather$time_hour</code>.</li>
|
||
</ul><p>These relationships are summarized visually in <a href="#fig-flights-relationships" data-type="xref">#fig-flights-relationships</a>.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-flights-relationships"><p><img src="diagrams/relational.png" alt="The relationships between airports, planes, flights, weather, and airlines datasets from the nycflights13 package. airports$faa connected to the flights$origin and flights$dest. planes$tailnum is connected to the flights$tailnum. weather$time_hour and weather$origin are jointly connected to flights$time_hour and flights$origin. airlines$carrier is connected to flights$carrier. There are no direct connections between airports, planes, airlines, and weather data frames." width="502"/></p>
|
||
<figcaption>Connections between all five data frames in the nycflights13 package. Variables making up a primary key are coloured grey, and are connected to their corresponding foreign keys with arrows.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
<p>You’ll notice a nice feature in the design of these keys: the primary and foreign keys almost always have the same names, which, as you’ll see shortly, will make your joining life much easier. It’s also worth noting the opposite relationship: almost every variable name used in multiple tables has the same meaning in each place. There’s only one exception: <code>year</code> means year of departure in <code>flights</code> and year of manufacturer in <code>planes</code>. This will become important when we start actually joining tables together.</p>
|
||
</section>
|
||
|
||
<section id="checking-primary-keys" data-type="sect2">
|
||
<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 |>
|
||
count(tailnum) |>
|
||
filter(n > 1)
|
||
#> # A tibble: 0 × 2
|
||
#> # … with 2 variables: tailnum <chr>, n <int>
|
||
|
||
weather |>
|
||
count(time_hour, origin) |>
|
||
filter(n > 1)
|
||
#> # A tibble: 0 × 3
|
||
#> # … with 3 variables: time_hour <dttm>, origin <chr>, n <int></pre>
|
||
</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 |>
|
||
filter(is.na(tailnum))
|
||
#> # A tibble: 0 × 9
|
||
#> # … with 9 variables: tailnum <chr>, year <int>, type <chr>,
|
||
#> # manufacturer <chr>, model <chr>, engines <int>, seats <int>, speed <int>,
|
||
#> # engine <chr>
|
||
|
||
weather |>
|
||
filter(is.na(time_hour) | is.na(origin))
|
||
#> # A tibble: 0 × 15
|
||
#> # … with 15 variables: origin <chr>, year <int>, month <int>, day <int>,
|
||
#> # hour <int>, temp <dbl>, dewp <dbl>, humid <dbl>, wind_dir <dbl>,
|
||
#> # wind_speed <dbl>, wind_gust <dbl>, precip <dbl>, pressure <dbl>,
|
||
#> # visib <dbl>, time_hour <dttm></pre>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="surrogate-keys" data-type="sect2">
|
||
<h2>
|
||
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 |>
|
||
count(time_hour, carrier, flight) |>
|
||
filter(n > 1)
|
||
#> # A tibble: 0 × 4
|
||
#> # … with 4 variables: time_hour <dttm>, carrier <chr>, flight <int>, n <int></pre>
|
||
</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 |>
|
||
count(alt, lat) |>
|
||
filter(n > 1)
|
||
#> # A tibble: 1 × 3
|
||
#> alt lat n
|
||
#> <dbl> <dbl> <int>
|
||
#> 1 13 40.6 2</pre>
|
||
</div>
|
||
<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 |>
|
||
mutate(id = row_number(), .before = 1)
|
||
flights2
|
||
#> # A tibble: 336,776 × 20
|
||
#> id year month day dep_time sched_dep_t…¹ dep_d…² arr_t…³ sched…⁴ arr_d…⁵
|
||
#> <int> <int> <int> <int> <int> <int> <dbl> <int> <int> <dbl>
|
||
#> 1 1 2013 1 1 517 515 2 830 819 11
|
||
#> 2 2 2013 1 1 533 529 4 850 830 20
|
||
#> 3 3 2013 1 1 542 540 2 923 850 33
|
||
#> 4 4 2013 1 1 544 545 -1 1004 1022 -18
|
||
#> 5 5 2013 1 1 554 600 -6 812 837 -25
|
||
#> 6 6 2013 1 1 554 558 -4 740 728 12
|
||
#> # … with 336,770 more rows, 10 more variables: carrier <chr>, flight <int>,
|
||
#> # tailnum <chr>, origin <chr>, dest <chr>, air_time <dbl>, distance <dbl>,
|
||
#> # hour <dbl>, minute <dbl>, time_hour <dttm>, and abbreviated variable names
|
||
#> # ¹sched_dep_time, ²dep_delay, ³arr_time, ⁴sched_arr_time, ⁵arr_delay</pre>
|
||
</div>
|
||
<p>Surrogate keys can be particular useful when communicating to other humans: it’s much easier to tell someone to take a look at flight 2001 than to say look at UA430 which departed 9am 2013-01-03.</p>
|
||
</section>
|
||
|
||
<section id="exercises" data-type="sect2">
|
||
<h2>
|
||
Exercises</h2>
|
||
<ol type="1"><li><p>We forgot to draw the relationship between <code>weather</code> and <code>airports</code> in <a href="#fig-flights-relationships" data-type="xref">#fig-flights-relationships</a>. What is the relationship and how should it appear in the diagram?</p></li>
|
||
<li><p><code>weather</code> only contains information for the three origin airports in NYC. If it contained weather records for all airports in the USA, what additional connection would it make to <code>flights</code>?</p></li>
|
||
<li><p>The <code>year</code>, <code>month</code>, <code>day</code>, <code>hour</code>, and <code>origin</code> variables almost form a compound key for <code>weather</code>, but there’s one hour that has duplicate observations. Can you figure out what’s special about that hour?</p></li>
|
||
<li><p>We know that some days of the year are special and fewer people than usual fly on them (e.g. Christmas eve and Christmas day). How might you represent that data as a data frame? What would be the primary key? How would it connect to the existing data frames?</p></li>
|
||
<li><p>Draw a diagram illustrating the connections between the <code>Batting</code>, <code>People</code>, and <code>Salaries</code> data frames in the Lahman package. Draw another diagram that shows the relationship between <code>People</code>, <code>Managers</code>, <code>AwardsManagers</code>. How would you characterise the relationship between the <code>Batting</code>, <code>Pitching</code>, and <code>Fielding</code> data frames?</p></li>
|
||
</ol></section>
|
||
</section>
|
||
|
||
<section id="sec-mutating-joins" data-type="sect1">
|
||
<h1>
|
||
Basic joins</h1>
|
||
<p>Now that you understand how data frames are connected via keys, we can start using joins to better understand the <code>flights</code> dataset. dplyr provides six join functions: <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">left_join()</a></code>, <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">inner_join()</a></code>, <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">right_join()</a></code>, <code><a href="https://dplyr.tidyverse.org/reference/filter-joins.html">semi_join()</a></code>, and <code><a href="https://dplyr.tidyverse.org/reference/filter-joins.html">anti_join()</a></code>. They all have the same interface: they take a pair of data frames (<code>x</code> and <code>y</code>) and return a data frame. The order of the rows and columns in the output is primarily determined by <code>x</code>.</p>
|
||
<p>In this section, you’ll learn how to use one mutating join, <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">left_join()</a></code>, and two filtering joins, <code><a href="https://dplyr.tidyverse.org/reference/filter-joins.html">semi_join()</a></code> and <code><a href="https://dplyr.tidyverse.org/reference/filter-joins.html">anti_join()</a></code>. In the next section, you’ll learn exactly how these functions work, and about the remaining <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">inner_join()</a></code>, <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">right_join()</a></code> and <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">full_join()</a></code>.</p>
|
||
|
||
<section id="mutating-joins" data-type="sect2">
|
||
<h2>
|
||
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 |>
|
||
select(year, time_hour, origin, dest, tailnum, carrier)
|
||
flights2
|
||
#> # A tibble: 336,776 × 6
|
||
#> year time_hour origin dest tailnum carrier
|
||
#> <int> <dttm> <chr> <chr> <chr> <chr>
|
||
#> 1 2013 2013-01-01 05:00:00 EWR IAH N14228 UA
|
||
#> 2 2013 2013-01-01 05:00:00 LGA IAH N24211 UA
|
||
#> 3 2013 2013-01-01 05:00:00 JFK MIA N619AA AA
|
||
#> 4 2013 2013-01-01 05:00:00 JFK BQN N804JB B6
|
||
#> 5 2013 2013-01-01 06:00:00 LGA ATL N668DN DL
|
||
#> 6 2013 2013-01-01 05:00:00 EWR ORD N39463 UA
|
||
#> # … with 336,770 more rows</pre>
|
||
</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 |>
|
||
left_join(airlines)
|
||
#> Joining with `by = join_by(carrier)`
|
||
#> # A tibble: 336,776 × 7
|
||
#> year time_hour origin dest tailnum carrier name
|
||
#> <int> <dttm> <chr> <chr> <chr> <chr> <chr>
|
||
#> 1 2013 2013-01-01 05:00:00 EWR IAH N14228 UA United Air Lines Inc.
|
||
#> 2 2013 2013-01-01 05:00:00 LGA IAH N24211 UA United Air Lines Inc.
|
||
#> 3 2013 2013-01-01 05:00:00 JFK MIA N619AA AA American Airlines Inc.
|
||
#> 4 2013 2013-01-01 05:00:00 JFK BQN N804JB B6 JetBlue Airways
|
||
#> 5 2013 2013-01-01 06:00:00 LGA ATL N668DN DL Delta Air Lines Inc.
|
||
#> 6 2013 2013-01-01 05:00:00 EWR ORD N39463 UA United Air Lines Inc.
|
||
#> # … with 336,770 more rows</pre>
|
||
</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 |>
|
||
left_join(weather |> select(origin, time_hour, temp, wind_speed))
|
||
#> Joining with `by = join_by(time_hour, origin)`
|
||
#> # A tibble: 336,776 × 8
|
||
#> year time_hour origin dest tailnum carrier temp wind_speed
|
||
#> <int> <dttm> <chr> <chr> <chr> <chr> <dbl> <dbl>
|
||
#> 1 2013 2013-01-01 05:00:00 EWR IAH N14228 UA 39.0 12.7
|
||
#> 2 2013 2013-01-01 05:00:00 LGA IAH N24211 UA 39.9 15.0
|
||
#> 3 2013 2013-01-01 05:00:00 JFK MIA N619AA AA 39.0 15.0
|
||
#> 4 2013 2013-01-01 05:00:00 JFK BQN N804JB B6 39.0 15.0
|
||
#> 5 2013 2013-01-01 06:00:00 LGA ATL N668DN DL 39.9 16.1
|
||
#> 6 2013 2013-01-01 05:00:00 EWR ORD N39463 UA 39.0 12.7
|
||
#> # … with 336,770 more rows</pre>
|
||
</div>
|
||
<p>Or what size of plane was flying:</p>
|
||
<div class="cell">
|
||
<pre data-type="programlisting" data-code-language="downlit">flights2 |>
|
||
left_join(planes |> select(tailnum, type, engines, seats))
|
||
#> Joining with `by = join_by(tailnum)`
|
||
#> # A tibble: 336,776 × 9
|
||
#> year time_hour origin dest tailnum carrier type engines seats
|
||
#> <int> <dttm> <chr> <chr> <chr> <chr> <chr> <int> <int>
|
||
#> 1 2013 2013-01-01 05:00:00 EWR IAH N14228 UA Fixed wi… 2 149
|
||
#> 2 2013 2013-01-01 05:00:00 LGA IAH N24211 UA Fixed wi… 2 149
|
||
#> 3 2013 2013-01-01 05:00:00 JFK MIA N619AA AA Fixed wi… 2 178
|
||
#> 4 2013 2013-01-01 05:00:00 JFK BQN N804JB B6 Fixed wi… 2 200
|
||
#> 5 2013 2013-01-01 06:00:00 LGA ATL N668DN DL Fixed wi… 2 178
|
||
#> 6 2013 2013-01-01 05:00:00 EWR ORD N39463 UA Fixed wi… 2 191
|
||
#> # … with 336,770 more rows</pre>
|
||
</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 |>
|
||
filter(tailnum == "N3ALAA") |>
|
||
left_join(planes |> select(tailnum, type, engines, seats))
|
||
#> Joining with `by = join_by(tailnum)`
|
||
#> # A tibble: 63 × 9
|
||
#> year time_hour origin dest tailnum carrier type engines seats
|
||
#> <int> <dttm> <chr> <chr> <chr> <chr> <chr> <int> <int>
|
||
#> 1 2013 2013-01-01 06:00:00 LGA ORD N3ALAA AA <NA> NA NA
|
||
#> 2 2013 2013-01-02 18:00:00 LGA ORD N3ALAA AA <NA> NA NA
|
||
#> 3 2013 2013-01-03 06:00:00 LGA ORD N3ALAA AA <NA> NA NA
|
||
#> 4 2013 2013-01-07 19:00:00 LGA ORD N3ALAA AA <NA> NA NA
|
||
#> 5 2013 2013-01-08 17:00:00 JFK ORD N3ALAA AA <NA> NA NA
|
||
#> 6 2013 2013-01-16 06:00:00 LGA ORD N3ALAA AA <NA> NA NA
|
||
#> # … with 57 more rows</pre>
|
||
</div>
|
||
<p>We’ll come back to this problem a few times in the rest of the chapter.</p>
|
||
</section>
|
||
|
||
<section id="specifying-join-keys" data-type="sect2">
|
||
<h2>
|
||
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 |>
|
||
left_join(planes)
|
||
#> Joining with `by = join_by(year, tailnum)`
|
||
#> # A tibble: 336,776 × 13
|
||
#> year time_hour origin dest tailnum carrier type manufactu…¹ model
|
||
#> <int> <dttm> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
|
||
#> 1 2013 2013-01-01 05:00:00 EWR IAH N14228 UA <NA> <NA> <NA>
|
||
#> 2 2013 2013-01-01 05:00:00 LGA IAH N24211 UA <NA> <NA> <NA>
|
||
#> 3 2013 2013-01-01 05:00:00 JFK MIA N619AA AA <NA> <NA> <NA>
|
||
#> 4 2013 2013-01-01 05:00:00 JFK BQN N804JB B6 <NA> <NA> <NA>
|
||
#> 5 2013 2013-01-01 06:00:00 LGA ATL N668DN DL <NA> <NA> <NA>
|
||
#> 6 2013 2013-01-01 05:00:00 EWR ORD N39463 UA <NA> <NA> <NA>
|
||
#> # … with 336,770 more rows, 4 more variables: engines <int>, seats <int>,
|
||
#> # speed <int>, engine <chr>, and abbreviated variable name ¹manufacturer</pre>
|
||
</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 |>
|
||
left_join(planes, join_by(tailnum))
|
||
#> # A tibble: 336,776 × 14
|
||
#> year.x time_hour origin dest tailnum carrier year.y type manuf…¹
|
||
#> <int> <dttm> <chr> <chr> <chr> <chr> <int> <chr> <chr>
|
||
#> 1 2013 2013-01-01 05:00:00 EWR IAH N14228 UA 1999 Fixed … BOEING
|
||
#> 2 2013 2013-01-01 05:00:00 LGA IAH N24211 UA 1998 Fixed … BOEING
|
||
#> 3 2013 2013-01-01 05:00:00 JFK MIA N619AA AA 1990 Fixed … BOEING
|
||
#> 4 2013 2013-01-01 05:00:00 JFK BQN N804JB B6 2012 Fixed … AIRBUS
|
||
#> 5 2013 2013-01-01 06:00:00 LGA ATL N668DN DL 1991 Fixed … BOEING
|
||
#> 6 2013 2013-01-01 05:00:00 EWR ORD N39463 UA 2012 Fixed … BOEING
|
||
#> # … with 336,770 more rows, 5 more variables: model <chr>, engines <int>,
|
||
#> # seats <int>, speed <int>, engine <chr>, and abbreviated variable name
|
||
#> # ¹manufacturer</pre>
|
||
</div>
|
||
<p>Note that the <code>year</code> variables are disambiguated in the output with a suffix (<code>year.x</code> and <code>year.y</code>), which tells you whether the variable came from the <code>x</code> or <code>y</code> argument. You can override the default suffixes with the <code>suffix</code> argument.</p>
|
||
<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 |>
|
||
left_join(airports, join_by(dest == faa))
|
||
#> # A tibble: 336,776 × 13
|
||
#> year time_hour origin dest tailnum carrier name lat lon alt
|
||
#> <int> <dttm> <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl>
|
||
#> 1 2013 2013-01-01 05:00:00 EWR IAH N14228 UA Geor… 30.0 -95.3 97
|
||
#> 2 2013 2013-01-01 05:00:00 LGA IAH N24211 UA Geor… 30.0 -95.3 97
|
||
#> 3 2013 2013-01-01 05:00:00 JFK MIA N619AA AA Miam… 25.8 -80.3 8
|
||
#> 4 2013 2013-01-01 05:00:00 JFK BQN N804JB B6 <NA> NA NA NA
|
||
#> 5 2013 2013-01-01 06:00:00 LGA ATL N668DN DL Hart… 33.6 -84.4 1026
|
||
#> 6 2013 2013-01-01 05:00:00 EWR ORD N39463 UA Chic… 42.0 -87.9 668
|
||
#> # … with 336,770 more rows, and 3 more variables: tz <dbl>, dst <chr>,
|
||
#> # tzone <chr>
|
||
|
||
flights2 |>
|
||
left_join(airports, join_by(origin == faa))
|
||
#> # A tibble: 336,776 × 13
|
||
#> year time_hour origin dest tailnum carrier name lat lon alt
|
||
#> <int> <dttm> <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl>
|
||
#> 1 2013 2013-01-01 05:00:00 EWR IAH N14228 UA Newa… 40.7 -74.2 18
|
||
#> 2 2013 2013-01-01 05:00:00 LGA IAH N24211 UA La G… 40.8 -73.9 22
|
||
#> 3 2013 2013-01-01 05:00:00 JFK MIA N619AA AA John… 40.6 -73.8 13
|
||
#> 4 2013 2013-01-01 05:00:00 JFK BQN N804JB B6 John… 40.6 -73.8 13
|
||
#> 5 2013 2013-01-01 06:00:00 LGA ATL N668DN DL La G… 40.8 -73.9 22
|
||
#> 6 2013 2013-01-01 05:00:00 EWR ORD N39463 UA Newa… 40.7 -74.2 18
|
||
#> # … with 336,770 more rows, and 3 more variables: tz <dbl>, dst <chr>,
|
||
#> # tzone <chr></pre>
|
||
</div>
|
||
<p>In older code you might see a different way of specifying the join keys, using a character vector:</p>
|
||
<ul><li>
|
||
<code>by = "x"</code> corresponds to <code>join_by(x)</code>.</li>
|
||
<li>
|
||
<code>by = c("a" = "x")</code> corresponds to <code>join_by(a == x)</code>.</li>
|
||
</ul><p>Now that it exists, we prefer <code><a href="https://dplyr.tidyverse.org/reference/join_by.html">join_by()</a></code> since it provides a clearer and more flexible specification.</p>
|
||
</section>
|
||
|
||
<section id="filtering-joins" data-type="sect2">
|
||
<h2>
|
||
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 |>
|
||
semi_join(flights2, join_by(faa == origin))
|
||
#> # A tibble: 3 × 8
|
||
#> faa name lat lon alt tz dst tzone
|
||
#> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <chr> <chr>
|
||
#> 1 EWR Newark Liberty Intl 40.7 -74.2 18 -5 A America/New_York
|
||
#> 2 JFK John F Kennedy Intl 40.6 -73.8 13 -5 A America/New_York
|
||
#> 3 LGA La Guardia 40.8 -73.9 22 -5 A America/New_York</pre>
|
||
</div>
|
||
<p>Or just the destinations:</p>
|
||
<div class="cell">
|
||
<pre data-type="programlisting" data-code-language="downlit">airports |>
|
||
semi_join(flights2, join_by(faa == dest))
|
||
#> # A tibble: 101 × 8
|
||
#> faa name lat lon alt tz dst tzone
|
||
#> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <chr> <chr>
|
||
#> 1 ABQ Albuquerque International Sunport 35.0 -107. 5355 -7 A Americ…
|
||
#> 2 ACK Nantucket Mem 41.3 -70.1 48 -5 A Americ…
|
||
#> 3 ALB Albany Intl 42.7 -73.8 285 -5 A Americ…
|
||
#> 4 ANC Ted Stevens Anchorage Intl 61.2 -150. 152 -9 A Americ…
|
||
#> 5 ATL Hartsfield Jackson Atlanta Intl 33.6 -84.4 1026 -5 A Americ…
|
||
#> 6 AUS Austin Bergstrom Intl 30.2 -97.7 542 -6 A Americ…
|
||
#> # … with 95 more rows</pre>
|
||
</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 |>
|
||
anti_join(airports, join_by(dest == faa)) |>
|
||
distinct(dest)
|
||
#> # A tibble: 4 × 1
|
||
#> dest
|
||
#> <chr>
|
||
#> 1 BQN
|
||
#> 2 SJU
|
||
#> 3 STT
|
||
#> 4 PSE</pre>
|
||
</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 |>
|
||
anti_join(planes, join_by(tailnum)) |>
|
||
distinct(tailnum)
|
||
#> # A tibble: 722 × 1
|
||
#> tailnum
|
||
#> <chr>
|
||
#> 1 N3ALAA
|
||
#> 2 N3DUAA
|
||
#> 3 N542MQ
|
||
#> 4 N730MQ
|
||
#> 5 N9EAMQ
|
||
#> 6 N532UA
|
||
#> # … with 716 more rows</pre>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="exercises-1" data-type="sect2">
|
||
<h2>
|
||
Exercises</h2>
|
||
<ol type="1"><li><p>Find the 48 hours (over the course of the whole year) that have the worst delays. Cross-reference it with the <code>weather</code> data. Can you see any patterns?</p></li>
|
||
<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 |>
|
||
count(dest, sort = TRUE) |>
|
||
head(10)</pre>
|
||
</div>
|
||
<p>How can you find all flights to those destinations?</p>
|
||
</li>
|
||
<li><p>Does every departing flight have corresponding weather data for that hour?</p></li>
|
||
<li><p>What do the tail numbers that don’t have a matching record in <code>planes</code> have in common? (Hint: one variable explains ~90% of the problems.)</p></li>
|
||
<li><p>Add a column to <code>planes</code> that lists every <code>carrier</code> that has flown that plane. You might expect that there’s an implicit relationship between plane and airline, because each plane is flown by a single airline. Confirm or reject this hypothesis using the tools you’ve learned in previous chapters.</p></li>
|
||
<li><p>Add the latitude and the longitude of the origin <em>and</em> destination airport to <code>flights</code>. Is it easier to rename the columns before or after the join?</p></li>
|
||
<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 |>
|
||
semi_join(flights, join_by(faa == dest)) |>
|
||
ggplot(aes(lon, lat)) +
|
||
borders("state") +
|
||
geom_point() +
|
||
coord_quickmap()</pre>
|
||
</div>
|
||
<p>You might want to use the <code>size</code> or <code>colour</code> of the points to display the average delay for each airport.</p>
|
||
</li>
|
||
<li><p>What happened on June 13 2013? Draw a map of the delays, and then use Google to cross-reference with the weather.</p></li>
|
||
</ol></section>
|
||
</section>
|
||
|
||
<section id="how-do-joins-work" data-type="sect1">
|
||
<h1>
|
||
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(
|
||
~key, ~val_x,
|
||
1, "x1",
|
||
2, "x2",
|
||
3, "x3"
|
||
)
|
||
y <- tribble(
|
||
~key, ~val_y,
|
||
1, "y1",
|
||
2, "y2",
|
||
4, "y3"
|
||
)</pre>
|
||
</div>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-setup"><p><img src="diagrams/join/setup.png" alt="x and y are two data frames with 2 columns and 3 rows, with contents as described in the text. The values of the keys are coloured: 1 is green, 2 is purple, 3 is orange, and 4 is yellow." width="160"/></p>
|
||
<figcaption>Graphical representation of two simple tables. The coloured <code>key</code> columns map background colour to key value. The grey columns represent the “value” columns that are carried along for the ride.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
<p><a href="#fig-join-setup2" data-type="xref">#fig-join-setup2</a> shows all potential matches between <code>x</code> and <code>y</code> as the intersection between lines drawn from each row of <code>x</code> and each row of <code>y</code>. The rows and columns in the output are primarily determined by <code>x</code>, so the <code>x</code> table is horizontal and lines up with the output.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-setup2"><p><img src="diagrams/join/setup2.png" alt="x and y are placed at right-angles, with horizonal lines extending from x and vertical lines extending from y. There are 3 rows in x and 3 rows in y, which leads to nine intersections representing nine potential matches." width="170"/></p>
|
||
<figcaption>To understand how joins work, it’s useful to think of every possible match. Here we show that with a grid of connecting lines.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
<p>In an actual join, matches will be indicated with dots, as in <a href="#fig-join-inner" data-type="xref">#fig-join-inner</a>. The number of dots equals the number of matches, which in turn equals the number of rows in the output, a new data frame that contains the key, the x values, and the y values. The join shown here is a so-called <strong>equi</strong> <strong>inner join</strong>, where rows match if the keys are equal, so that the output contains only the rows with keys that appear in both <code>x</code> and <code>y</code>. Equi-joins are the most common type of join, so we’ll typically omit the equi prefix, and just call it an inner join. We’ll come back to non-equi joins in <a href="#sec-non-equi-joins" data-type="xref">#sec-non-equi-joins</a>.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-inner"><p><img src="diagrams/join/inner.png" alt="x and y are placed at right-angles with lines forming a grid of potential matches. Keys 1 and 2 appear in both x and y, so we get a match, indicated by a dot. Each dot corresponds to a row in the output, so the resulting joined data frame has two rows." width="363"/></p>
|
||
<figcaption>An inner join matches each row in <code>x</code> to the row in <code>y</code> that has the same value of <code>key</code>. Each match becomes a row in the output.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
<p>An <strong>outer join</strong> keeps observations that appear in at least one of the data frames. These joins work by adding an additional “virtual” observation to each data frame. This observation has a key that matches if no other key matches, and values filled with <code>NA</code>. There are three types of outer joins:</p>
|
||
<ul><li>
|
||
<p>A <strong>left join</strong> keeps all observations in <code>x</code>, <a href="#fig-join-left" data-type="xref">#fig-join-left</a>. Every row of <code>x</code> is preserved in the output because it can fall back to matching a row of <code>NA</code>s in <code>y</code>.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-left"><p><img src="diagrams/join/left.png" alt="Compared to the previous diagram showing an inner join, the y table gets a new virtual row containin NA that will match any row in x that didn't otherwise match. This means that the output now has three rows. For key = 3, which matches this virtual row, val_y takes value NA." width="385"/></p>
|
||
<figcaption>A visual representation of the left join where every row in <code>x</code> appears in the output.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>A <strong>right join</strong> keeps all observations in <code>y</code>, <a href="#fig-join-right" data-type="xref">#fig-join-right</a>. Every row of <code>y</code> is preserved in the output because it can fall back to matching a row of <code>NA</code>s in <code>x</code>. The output still matches <code>x</code> as much as possible; any extra rows from <code>y</code> are added to the end.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-right"><p><img src="diagrams/join/right.png" alt="Compared to the previous diagram showing an left join, the x table now gains a virtual row so that every row in y gets a match in x. val_x contains NA for the row in y that didn't match x." width="380"/></p>
|
||
<figcaption>A visual representation of the right join where every row of <code>y</code> appears in the output.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>A <strong>full join</strong> keeps all observations that appear in <code>x</code> or <code>y</code>, <a href="#fig-join-full" data-type="xref">#fig-join-full</a>. Every row of <code>x</code> and <code>y</code> is included in the output because both <code>x</code> and <code>y</code> have a fall back row of <code>NA</code>s. Again, the output starts with all rows from <code>x</code>, followed by the remaining unmatched <code>y</code> rows.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-full"><p><img src="diagrams/join/full.png" alt="Now both x and y have a virtual row that always matches. The result has 4 rows: keys 1, 2, 3, and 4 with all values from val_x and val_y, however key 2, val_y and key 4, val_x are NAs since those keys don't have a match in the other data frames." width="388"/></p>
|
||
<figcaption>A visual representation of the full join where every row in <code>x</code> and <code>y</code> appears in the output.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
</ul><p>Another way to show how the types of outer join differ is with a Venn diagram, as in <a href="#fig-join-venn" data-type="xref">#fig-join-venn</a>. However, this is not a great representation because while it might jog your memory about which rows are preserved, it fails to illustrate what’s happening with the columns.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-venn"><p><img src="diagrams/join/venn.png" alt="Venn diagrams for inner, full, left, and right joins. Each join represented with two intersecting circles representing data frames x and y, with x on the right and y on the left. Shading indicates the result of the join." width="385"/></p>
|
||
<figcaption>Venn diagrams showing the difference between inner, left, right, and full joins.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
|
||
<section id="row-matching" data-type="sect2">
|
||
<h2>
|
||
Row matching</h2>
|
||
<p>So far we’ve explored what happens if a row in <code>x</code> matches zero or one rows in <code>y</code>. What happens if it matches more than one row? To understand what’s going let’s first narrow our focus to the <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">inner_join()</a></code> and then draw a picture, <a href="#fig-join-match-types" data-type="xref">#fig-join-match-types</a>.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-match-types"><p><img src="diagrams/join/match-types.png" alt="A join diagram where x has key values 1, 2, and 3, and y has key values 1, 2, 2. The output has three rows because key 1 matches one row, key 2 matches two rows, and key 3 matches zero rows." width="348"/></p>
|
||
<figcaption>The three ways a row in <code>x</code> can match. <code>x1</code> matches one row in <code>y</code>, <code>x2</code> matches two rows in <code>y</code>, <code>x3</code> matches zero rows in y. Note that while there are three rows in <code>x</code> and three rows in the output, there isn’t a direct correspondence between the rows.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
<p>There are three possible outcomes for a row in <code>x</code>:</p>
|
||
<ul><li>If it doesn’t match anything, it’s dropped.</li>
|
||
<li>If it matches 1 row in <code>y</code>, it’s preserved.</li>
|
||
<li>If it matches more than 1 row in <code>y</code>, it’s duplicated once for each match.</li>
|
||
</ul><p>In principle, this means that there’s no guaranteed correspondence between the rows in the output and the rows in the <code>x</code>:</p>
|
||
<ul><li>There might be fewer rows if some rows in <code>x</code> don’t match any rows in <code>y</code>.</li>
|
||
<li>There might be more rows if some rows in <code>x</code> match multiple rows in <code>y</code>.</li>
|
||
<li>There might be the same number of rows if every row in <code>x</code> matches one row in <code>y</code>.</li>
|
||
<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"))
|
||
df2 <- tibble(key = c(1, 2, 2), val_y = c("y1", "y2", "y3"))
|
||
|
||
df1 |>
|
||
inner_join(df2, join_by(key))
|
||
#> Warning in inner_join(df1, df2, join_by(key)): Each row in `x` is expected to match at most 1 row in `y`.
|
||
#> ℹ Row 2 of `x` matches multiple rows.
|
||
#> ℹ If multiple matches are expected, set `multiple = "all"` to silence this
|
||
#> warning.
|
||
#> # A tibble: 3 × 3
|
||
#> key val_x val_y
|
||
#> <dbl> <chr> <chr>
|
||
#> 1 1 x1 y1
|
||
#> 2 2 x2 y2
|
||
#> 3 2 x2 y3</pre>
|
||
</div>
|
||
<p>This is one reason we like <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">left_join()</a></code> — if it runs without warning, you know that each row of the output matches the row in the same position in <code>x</code>.</p>
|
||
<p>You can gain further control over row matching with two arguments:</p>
|
||
<ul><li>
|
||
<code>unmatched</code> controls what happens when a row in <code>x</code> fails to match any rows in <code>y</code>. It defaults to <code>"drop"</code> which will silently drop any unmatched rows.</li>
|
||
<li>
|
||
<code>multiple</code> controls what happens when a row in <code>x</code> matches more than one row in <code>y</code>. For equi-joins, it defaults to <code>"warn"</code> which emits a warning message if any rows have multiple matches.</li>
|
||
</ul><p>There are two common cases in which you might want to override these defaults: enforcing a one-to-one mapping or deliberately allowing the rows to increase.</p>
|
||
</section>
|
||
|
||
<section id="one-to-one-mapping" data-type="sect2">
|
||
<h2>
|
||
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)
|
||
df2 <- tibble(x = c(1, 1))
|
||
df3 <- tibble(x = 3)
|
||
|
||
df1 |>
|
||
inner_join(df2, join_by(x), unmatched = "error", multiple = "error")
|
||
#> Error in `inner_join()`:
|
||
#> ! Each row in `x` must match at most 1 row in `y`.
|
||
#> ℹ Row 1 of `x` matches multiple rows.
|
||
df1 |>
|
||
inner_join(df3, join_by(x), unmatched = "error", multiple = "error")
|
||
#> Error in `inner_join()`:
|
||
#> ! Each row of `x` must have a match in `y`.
|
||
#> ℹ Row 1 of `x` does not have a match.</pre>
|
||
</div>
|
||
<p>Note that <code>unmatched = "error"</code> is not useful with <code><a href="https://dplyr.tidyverse.org/reference/mutate-joins.html">left_join()</a></code> because, as described above, every row in <code>x</code> has a fallback match to a virtual row in <code>y</code>.</p>
|
||
</section>
|
||
|
||
<section id="allow-multiple-rows" data-type="sect2">
|
||
<h2>
|
||
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 |>
|
||
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 |>
|
||
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`.
|
||
#> ℹ Row 1 of `x` matches multiple rows.
|
||
#> ℹ If multiple matches are expected, set `multiple = "all"` to silence this
|
||
#> warning.</pre>
|
||
</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 |>
|
||
select(tailnum, type, engines, seats) |>
|
||
left_join(flights2, by = "tailnum", multiple = "all")
|
||
|
||
plane_flights
|
||
#> # A tibble: 284,170 × 9
|
||
#> tailnum type engines seats year time_hour origin dest carrier
|
||
#> <chr> <chr> <int> <int> <int> <dttm> <chr> <chr> <chr>
|
||
#> 1 N10156 Fixed wi… 2 55 2013 2013-01-10 06:00:00 EWR PIT EV
|
||
#> 2 N10156 Fixed wi… 2 55 2013 2013-01-10 10:00:00 EWR CHS EV
|
||
#> 3 N10156 Fixed wi… 2 55 2013 2013-01-10 15:00:00 EWR MSP EV
|
||
#> 4 N10156 Fixed wi… 2 55 2013 2013-01-11 06:00:00 EWR CMH EV
|
||
#> 5 N10156 Fixed wi… 2 55 2013 2013-01-11 11:00:00 EWR MCI EV
|
||
#> 6 N10156 Fixed wi… 2 55 2013 2013-01-11 18:00:00 EWR PWM EV
|
||
#> # … with 284,164 more rows</pre>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="sec-non-equi-joins" data-type="sect2">
|
||
<h2>
|
||
Filtering joins</h2>
|
||
<p>The number of matches also determines the behavior of the filtering joins. The semi-join keeps rows in <code>x</code> that have one or more matches in <code>y</code>, as in <a href="#fig-join-semi" data-type="xref">#fig-join-semi</a>. The anti-join keeps rows in <code>x</code> that match zero rows in <code>y</code>, as in <a href="#fig-join-anti" data-type="xref">#fig-join-anti</a>. In both cases, only the existence of a match is important; it doesn’t matter how many times it matches. This means that filtering joins never duplicate rows like mutating joins do.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-semi"><p><img src="diagrams/join/semi.png" alt="A join diagram with old friends x and y. In a semi join, only the presence of a match matters so the output contains the same columns as x." width="318"/></p>
|
||
<figcaption>In a semi-join it only matters that there is a match; otherwise values in <code>y</code> don’t affect the output.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-anti"><p><img src="diagrams/join/anti.png" alt="An anti-join is the inverse of a semi-join so matches are drawn with red lines indicating that they will be dropped from the output." width="317"/></p>
|
||
<figcaption>An anti-join is the inverse of a semi-join, dropping rows from <code>x</code> that have a match in <code>y</code>.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
</section>
|
||
|
||
<section id="non-equi-joins" data-type="sect1">
|
||
<h1>
|
||
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)
|
||
#> # A tibble: 3 × 4
|
||
#> key.x val_x key.y val_y
|
||
#> <dbl> <chr> <dbl> <chr>
|
||
#> 1 1 x1 1 y1
|
||
#> 2 2 x2 2 y2
|
||
#> 3 3 x3 NA <NA></pre>
|
||
</div>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-inner-both"><p><img src="diagrams/join/inner-both.png" alt="A join diagram showing an inner join betwen x and y. The result now includes four columns: key.x, val_x, key.y, and val_y. The values of key.x and key.y are identical, which is why we usually only show one. " width="415"/></p>
|
||
<figcaption>An left join showing both <code>x</code> and <code>y</code> keys in the output.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
<p>When we move away from equi-joins we’ll always show the keys, because the key values will often different. For example, instead of matching only when the <code>x$key</code> and <code>y$key</code> are equal, we could match whenever the <code>x$key</code> is greater than or equal to the <code>y$key</code>, leading to <a href="#fig-join-gte" data-type="xref">#fig-join-gte</a>. dplyr’s join functions understand this distinction equi and non-equi joins so will always show both keys when you perform a non-equi join.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-gte"><p><img src="diagrams/join/gte.png" alt="A join diagram illustrating join_by(key >= key). The first row of x matches one row of y and the second and thirds rows each match two rows. This means the output has five rows containing each of the following (key.x, key.y) pairs: (1, 1), (2, 1), (2, 2), (3, 1), (3, 2)." width="385"/></p>
|
||
<figcaption>A non-equi join where the <code>x</code> key must greater than or equal to than the <code>y</code> key. Many rows generate multiple matches.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
<p>Non-equi-join isn’t a particularly useful term because it only tells you what the join is not, not what it is. dplyr helps by identifying four particularly useful types of non-equi-join:</p>
|
||
<ul><li>
|
||
<strong>Cross joins</strong> match every pair of rows.</li>
|
||
<li>
|
||
<strong>Inequality joins</strong> use <code><</code>, <code><=</code>, <code>></code>, and <code>>=</code> instead of <code>==</code>.</li>
|
||
<li>
|
||
<strong>Rolling joins</strong> are similar to inequality joins but only find the closest match.</li>
|
||
<li>
|
||
<strong>Overlap joins</strong> are a special type of inequality join designed to work with ranges.</li>
|
||
</ul><p>Each of these is described in more detail in the following sections.</p>
|
||
|
||
<section id="cross-joins" data-type="sect2">
|
||
<h2>
|
||
Cross joins</h2>
|
||
<p>A cross join matches everything, as in <a href="#fig-join-cross" data-type="xref">#fig-join-cross</a>, generating the Cartesian product of rows. This means the output will have <code>nrow(x) * nrow(y)</code> rows.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-cross"><p><img src="diagrams/join/cross.png" alt="A join diagram showing a dot for every combination of x and y." width="155"/></p>
|
||
<figcaption>A cross join matches each row in <code>x</code> with every row in <code>y</code>.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</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"))
|
||
df |> left_join(df, join_by())
|
||
#> # A tibble: 16 × 2
|
||
#> name.x name.y
|
||
#> <chr> <chr>
|
||
#> 1 John John
|
||
#> 2 John Simon
|
||
#> 3 John Tracy
|
||
#> 4 John Max
|
||
#> 5 Simon John
|
||
#> 6 Simon Simon
|
||
#> # … with 10 more rows</pre>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="inequality-joins" data-type="sect2">
|
||
<h2>
|
||
Inequality joins</h2>
|
||
<p>Inequality joins use <code><</code>, <code><=</code>, <code>>=</code>, or <code>></code> to restrict the set of possible matches, as in <a href="#fig-join-gte" data-type="xref">#fig-join-gte</a> and <a href="#fig-join-lt" data-type="xref">#fig-join-lt</a>.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-lt"><p><img src="diagrams/join/lt.png" width="185"/></p>
|
||
<figcaption>An inequality join where <code>x</code> is joined to <code>y</code> on rows where the key of <code>x</code> is less than the key of <code>y</code>. This makes a triangular shape in the top-left corner.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</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"))
|
||
|
||
df |> left_join(df, join_by(id < id))
|
||
#> # A tibble: 7 × 4
|
||
#> id.x name.x id.y name.y
|
||
#> <int> <chr> <int> <chr>
|
||
#> 1 1 John 2 Simon
|
||
#> 2 1 John 3 Tracy
|
||
#> 3 1 John 4 Max
|
||
#> 4 2 Simon 3 Tracy
|
||
#> 5 2 Simon 4 Max
|
||
#> 6 3 Tracy 4 Max
|
||
#> # … with 1 more row</pre>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="rolling-joins" data-type="sect2">
|
||
<h2>
|
||
Rolling joins</h2>
|
||
<p>Rolling joins are a special type of inequality join where instead of getting <em>every</em> row that satisfies the inequality, you get just the closest row, as in <a href="#fig-join-closest" data-type="xref">#fig-join-closest</a>. You can turn any inequality join into a rolling join by adding <code>closest()</code>. For example <code>join_by(closest(x <= y))</code> matches the smallest <code>y</code> that’s greater than or equal to x, and <code>join_by(closest(x > y))</code> matches the biggest <code>y</code> that’s less than <code>x</code>.</p>
|
||
<div class="cell">
|
||
<div class="cell-output-display">
|
||
|
||
<figure id="fig-join-closest"><p><img src="diagrams/join/closest.png" alt="A rolling join is a subset of an inequality join so some matches are grayed out indicating that they're not used because they're not the "closest"." width="262"/></p>
|
||
<figcaption>A following join is similar to a greater-than-or-equal inequality join but only matches the first value.</figcaption>
|
||
</figure>
|
||
</div>
|
||
</div>
|
||
<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(
|
||
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(
|
||
name = wakefield::name(100),
|
||
birthday = lubridate::ymd("2022-01-01") + (sample(365, 100, replace = TRUE) - 1)
|
||
)
|
||
employees
|
||
#> # A tibble: 100 × 2
|
||
#> name birthday
|
||
#> <variable> <date>
|
||
#> 1 Lindzy 2022-08-11
|
||
#> 2 Santania 2022-03-01
|
||
#> 3 Gardell 2022-03-04
|
||
#> 4 Cyrille 2022-11-15
|
||
#> 5 Kynli 2022-07-09
|
||
#> 6 Sever 2022-02-03
|
||
#> # … with 94 more rows</pre>
|
||
</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 |>
|
||
left_join(parties, join_by(closest(birthday >= party)))
|
||
#> # A tibble: 100 × 4
|
||
#> name birthday q party
|
||
#> <variable> <date> <int> <date>
|
||
#> 1 Lindzy 2022-08-11 3 2022-07-11
|
||
#> 2 Santania 2022-03-01 1 2022-01-10
|
||
#> 3 Gardell 2022-03-04 1 2022-01-10
|
||
#> 4 Cyrille 2022-11-15 4 2022-10-03
|
||
#> 5 Kynli 2022-07-09 2 2022-04-04
|
||
#> 6 Sever 2022-02-03 1 2022-01-10
|
||
#> # … with 94 more rows</pre>
|
||
</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 |>
|
||
anti_join(parties, join_by(closest(birthday >= party)))
|
||
#> # A tibble: 4 × 2
|
||
#> name birthday
|
||
#> <variable> <date>
|
||
#> 1 Janeida 2022-01-04
|
||
#> 2 Aires 2022-01-07
|
||
#> 3 Mikalya 2022-01-06
|
||
#> 4 Carlynn 2022-01-08</pre>
|
||
</div>
|
||
<p>To resolve that issue we’ll need to tackle the problem a different way, with overlap joins.</p>
|
||
</section>
|
||
|
||
<section id="overlap-joins" data-type="sect2">
|
||
<h2>
|
||
Overlap joins</h2>
|
||
<p>Overlap joins provide three helpers that use inequality joins to make it easier to work with intervals:</p>
|
||
<ul><li>
|
||
<code>between(x, y_lower, y_upper)</code> is short for <code>x >= y_lower, x <= y_upper</code>.</li>
|
||
<li>
|
||
<code>within(x_lower, x_upper, y_lower, y_upper)</code> is short for <code>x_lower >= y_lower, x_upper <= y_upper</code>.</li>
|
||
<li>
|
||
<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(
|
||
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")),
|
||
end = lubridate::ymd(c("2022-04-03", "2022-07-11", "2022-10-02", "2022-12-31"))
|
||
)
|
||
parties
|
||
#> # A tibble: 4 × 4
|
||
#> q party start end
|
||
#> <int> <date> <date> <date>
|
||
#> 1 1 2022-01-10 2022-01-01 2022-04-03
|
||
#> 2 2 2022-04-04 2022-04-04 2022-07-11
|
||
#> 3 3 2022-07-11 2022-07-11 2022-10-02
|
||
#> 4 4 2022-10-03 2022-10-03 2022-12-31</pre>
|
||
</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 |>
|
||
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
|
||
#> start.x end.x start.y end.y
|
||
#> <date> <date> <date> <date>
|
||
#> 1 2022-04-04 2022-07-11 2022-07-11 2022-10-02</pre>
|
||
</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(
|
||
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")),
|
||
end = lubridate::ymd(c("2022-04-03", "2022-07-10", "2022-10-02", "2022-12-31"))
|
||
)</pre>
|
||
</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 |>
|
||
inner_join(parties, join_by(between(birthday, start, end)), unmatched = "error")
|
||
#> # A tibble: 100 × 6
|
||
#> name birthday q party start end
|
||
#> <variable> <date> <int> <date> <date> <date>
|
||
#> 1 Lindzy 2022-08-11 3 2022-07-11 2022-07-11 2022-10-02
|
||
#> 2 Santania 2022-03-01 1 2022-01-10 2022-01-01 2022-04-03
|
||
#> 3 Gardell 2022-03-04 1 2022-01-10 2022-01-01 2022-04-03
|
||
#> 4 Cyrille 2022-11-15 4 2022-10-03 2022-10-03 2022-12-31
|
||
#> 5 Kynli 2022-07-09 2 2022-04-04 2022-04-04 2022-07-10
|
||
#> 6 Sever 2022-02-03 1 2022-01-10 2022-01-01 2022-04-03
|
||
#> # … with 94 more rows</pre>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="exercises-2" data-type="sect2">
|
||
<h2>
|
||
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")
|
||
#> # A tibble: 4 × 3
|
||
#> key val_x val_y
|
||
#> <dbl> <chr> <chr>
|
||
#> 1 1 x1 y1
|
||
#> 2 2 x2 y2
|
||
#> 3 3 x3 <NA>
|
||
#> 4 4 <NA> y3
|
||
|
||
x |> full_join(y, by = "key", keep = TRUE)
|
||
#> # A tibble: 4 × 4
|
||
#> key.x val_x key.y val_y
|
||
#> <dbl> <chr> <dbl> <chr>
|
||
#> 1 1 x1 1 y1
|
||
#> 2 2 x2 2 y2
|
||
#> 3 3 x3 NA <NA>
|
||
#> 4 NA <NA> 4 y3</pre>
|
||
</div>
|
||
</li>
|
||
<li><p>When finding if any party period overlapped with another party period we used <code>q < q</code> in the <code><a href="https://dplyr.tidyverse.org/reference/join_by.html">join_by()</a></code>? Why? What happens if you remove this inequality?</p></li>
|
||
</ol></section>
|
||
</section>
|
||
|
||
<section id="summary" data-type="sect1">
|
||
<h1>
|
||
Summary</h1>
|
||
<p>In this chapter, you’ve learned how to use mutating and filtering joins to combine data from a pair of data frames. Along the way you learned how to identify keys, and the difference between primary and foreign keys. You also understand how joins work and how to figure out how many rows the output will have. Finally, you’ve gained a glimpse into the power of non-equi-joins and seen a few interesting use cases.</p>
|
||
<p>This chapter concludes the “Transform” part of the book where the focus was on the tools you could use with individual columns and tibbles. You learned about dplyr and base functions for working with logical vectors, numbers, and complete tables, stringr functions for working strings, lubridate functions for working with date-times, and forcats functions for working with factors.</p>
|
||
<p>In the next part of the book, you’ll learn more about getting various types of data into R in a tidy form.</p>
|
||
|
||
|
||
</section>
|
||
</section>
|