More about keys

This commit is contained in:
hadley 2016-01-15 07:05:45 -06:00
parent 61a0356444
commit 74346796b6
4 changed files with 67 additions and 35 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

View File

@ -14,9 +14,11 @@ options(dplyr.print_min = 6, dplyr.print_max = 6)
knitr::opts_chunk$set(fig.path = "figures/", cache = TRUE)
```
It's rare that a data analysis involves only a single table of data. Typically you have many tables of data, and you have to combine them to answer the questions that you're interested in. This type of data is called __relational__ because it concerns the relations between multiple datasets.
It's rare that a data analysis involves only a single table of data. Typically you have many tables of data, and you must combine them to answer the questions that you're interested in. Collectively, multiple tables of data are called __relational data__ because it is the relations, not just the individual datasets, that are particularly important.
Relations are always defined between a pair of tables. (But that pair might be the same table, a so called self-join.) The relationships of three or more tables are always a property of the relations between each pair. To work with relational data you need verbs that work with pairs of tables. There are three families of verbs design to work with relational data:
Relations are always defined between a pair of tables. All other relations are built up from this simple idea: the relations of three or more tables are always a property of the relations between each pair; sometimes both elements of a pair can be the same table.
To work with relational data you need verbs that work with pairs of tables. There are three families of verbs design to work with relational data:
* __Mutating joins__, which add new variables to one data frame from matching
rows in another.
@ -26,11 +28,11 @@ Relations are always defined between a pair of tables. (But that pair might be t
* __Set operations__, which treat observations like they were set elements.
The most common place to find relational data _relational_ database management system, which encompasses almost all modern databases. If you've used a database before, you've almost certainly used SQL. If so, you should find the concepts in this chapter familiar, although their expression in dplyr is little different. Generally, dplyr is a little easier to use than SQL because it's specialised to data analysis: it makes common data analysis operations easier, at the expense of making it difficult to do other things.
The most common place to find relational data is in a _relational_ database management system, a term that encompasses almost all modern databases. If you've used a database before, you've almost certainly used SQL. If so, you should find the concepts in this chapter familiar, although their expression in dplyr is little different. Generally, dplyr is a little easier to use than SQL because it's specialised to data analysis: it makes common data analysis operations easier, at the expense of making it difficult to do other things.
## nycflights13 {#nycflights13-relational}
You'll learn about relational data with other data from nycflights13. As well as the `flights` table that you've worked with so far, nycflights13 contains a four related data frames:
You'll learn about relational data with other datasets from the nycflights13 package. As well as the `flights` table that you've worked with so far, nycflights13 contains a four related data frames:
* `airlines` lets you look up the full carrier name from its abbreviated
code:
@ -64,7 +66,7 @@ One way to show the relationships between the different tables is with a drawing
knitr::include_graphics("diagrams/relational-nycflights.png")
```
This diagram is a little overwhelming, and it's simple compared to some you'll see in the wild! The key to understanding diagrams like this is to remember each relation always concerns a pair of tables. You don't need to understand the whole thing; you just need the understand the chain of relations between the tables that you are interested in.
This diagram is a little overwhelming, and even so it's simple compared to some you'll see in the wild! The key to understanding diagrams like this is to remember each relation always concerns a pair of tables. You don't need to understand the whole thing; you just need the understand the chain of relations between the tables that you are interested in.
For nycflights13:
@ -77,18 +79,6 @@ For nycflights13:
* `flights` connects to `weather` via `origin` (the location), and
`year`, `month`, `day` and `hour` (the time).
The variables used to connect each pair of tables are called __keys__:
* The __primary key__ uniquely identifies an observation in the current table.
* The __foreign key__ uniquely identifies an observation in another table.
In simple cases, a single variable is sufficient to identify an observation. For example, each plane is uniquely identified by its `tailnum`. In other cases, multiple variables may be needed. For example, to identify an observation in `weather` you need five variables: `year`, `month`, `day`, `hour`, and `origin`.
Each relation (an arrow) matches a primary keys (coloured grey) with the corresponding foreign key (the arrowhead) in another table.
Relations are implicitly one-to-many. For example, each flight has one plane, but each plane has many flights. In other data, you'll occassionaly see a 1-to-1 relationship. You can think of this as a special case of 1-to-many. It's possible to model many-to-many relations with a many-to-1 relation plus a 1-to-many relation. For example, in this data there's a many-to-many relationship between airlines and airports: each airport flies to many airlines; each airport hosts many airlines.
### Exercises
1. Imagine you want to draw (approximately) the route each plane flies from
@ -111,6 +101,60 @@ Relations are implicitly one-to-many. For example, each flight has one plane, bu
What would be the primary keys of that table? How would it connect to the
existing tables?
## Keys
The variables used to connect each pair of tables are called __keys__. A key is a variable (or set of variables) that uniquely identifies an observation. In simple cases, a single variable is sufficient to identify an observation. For example, each plane is uniquely identified by its `tailnum`. In other cases, multiple variables may be needed. For example, to identify an observation in `weather` you need five variables: `year`, `month`, `day`, `hour`, and `origin`.
There are two types of keys:
* A __primary key__ uniquely identifies an observation in its own table.
For example, `planes$tailnum` is a primary key because it uniquely identifies
each plane.
* A __foreign key__ uniquely identifies an observation in another table.
For example, the `flights$tailnum` is a foregin key because it matches each
flight to a unique plane.
A variable can be both part of primary key _and_ a foreign key. For example, `origin` is part of the `weather` primary key, and is also a foreign key for the `airport` table.
Once you've identified the primary keys in your tables, it's good practice to verify that they do indeed uniquely identify each observation. One way to do that is `count()` the primary keys and look for entries where `n` is greater than one:
```{r}
planes %>% count(tailnum) %>% filter(n > 1)
weather %>% count(year, month, day, hour, origin) %>% filter(n > 1)
```
Sometimes a table does't have an explicit primary key: each row is an observation, but no combination of variables reliably identifies it. For example, what's the primary key in the `flights` table? You might think it would be the date plus the flight or tail number, but neither of those are unique:
```{r}
flights %>% count(year, month, day, flight) %>% filter(n > 1)
flights %>% count(year, month, day, tailnum) %>% filter(n > 1)
```
If a table lacks a primary key, it's sometimes useful to add one:
```{r}
flights %>% mutate(id = row_number())
```
A primary key and the corresponding foreign key in another table form a __relation__. Relations are typically one-to-many. For example, each flight has one plane, but each plane has many flights. In other data, you'll occassionaly see a 1-to-1 relationship. You can think of this as a special case of 1-to-many. It's possible to model many-to-many relations with a many-to-1 relation plus a 1-to-many relation. For example, in this data there's a many-to-many relationship between airlines and airports: each airport flies to many airlines; each airport hosts many airlines.
### Exercises
1. Identify the keys in the following datasets
1. `Lahman::Batting`,
1. `babynames::babynames`
1. `nasaweather::atmos`
1. `fueleconomy::vehicles`
1. Draw a diagram illustrating the connections between the `Batting`,
`Master`, and `Salary` tables in the Lahman package. Draw another diagram
that shows the relationship between `Master`, `Managers`, `AwardsManagers`.
How would you characterise the relationship between the `Batting`,
`Pitching`, and `Fielding` tables?
## Mutating joins {#mutating-joins}
The first tool we'll look at for combining a pair of tables is the __mutating join__. A mutating join allows you to combine variables from two tables. It first matches observations by their keys, then copies across variables from one table to the other.
@ -169,7 +213,6 @@ In an actual join, matches will be indicated with dots. The colour of the dots m
knitr::include_graphics("diagrams/join-inner.png")
```
### Inner join {#inner-join}
The simplest type of join is the __inner join__. An inner join matches pairs of observations whenever their keys are equal:
@ -212,13 +255,13 @@ Another way to depict the different types of joins is with a Venn diagram:
knitr::include_graphics("diagrams/join-venn.png")
```
However, this is not a great representation. It might jog your memory about which join preserves the observations in which table, but it suffers from a major limitation. A Venn diagram can't show what happens when keys don't uniquely identify an observation.
However, this is not a great representation. It might jog your memory about which join preserves the observations in which table, but it suffers from a major limitation: a Venn diagram can't show what happens when keys don't uniquely identify an observation.
### Duplicate keys {#join-matches}
So far all the diagrams have assumed that the keys are unique. But obviously that's not always the case. This section explains what happens when the keys are not unique. There are two possibilities:
So far all the diagrams have assumed that the keys are unique. But that's not always the case. This section explains what happens when the keys are not unique. There are two possibilities:
1. There are duplicate foreign keys. This is useful when you want to
1. One table has duplicate keys. This is useful when you want to
add in additional information as there is typically a one-to-many
relationship.
@ -236,13 +279,9 @@ So far all the diagrams have assumed that the keys are unique. But obviously tha
left_join(x, y, by = "key")
```
1. There are duplicate primary keys. This means that the keys do not uniquely
identify an observation. Technically, that means the variable is not a
primary key. However, that often happens because of a data entry error.
It's _supposed_ to be primary key, so its still useful to call it that.
When the primary key is duplicated, you get all possible combinations,
the Cartesian product:
1. Both tables have duplicate keys. This is usually an error because in
neither table do the keys uniquely identify an observation. When you join
duplicated keys, you get all possible combinations, the Cartesian product:
```{r, echo = FALSE, out.width = "75%"}
knitr::include_graphics("diagrams/join-many-to-many.png")
@ -254,13 +293,6 @@ So far all the diagrams have assumed that the keys are unique. But obviously tha
left_join(x, y, by = "key")
```
Once you've identified the primary keys in your tables, it's good practice to verify that they do indeed uniquely identify each observation. One way to do that is `count()` the primary keys and look for entries where `n` is greater than one:
```{r}
planes %>% count(tailnum) %>% filter(n > 1)
weather %>% count(year, month, day, hour, origin) %>% filter(n > 1)
```
### Defining the key columns {#join-by}
So far, the pairs of tables have always been joined by a single variable, and that variable has the same name in both tables. That constraint was encoded by `by = "key"`. You can use other values for `by` to connect the tables in other ways: