From 0c4b8dcd04ce9a7811d0414e4a15009181ef0729 Mon Sep 17 00:00:00 2001 From: Mine Cetinkaya-Rundel Date: Wed, 21 Apr 2021 13:25:51 +0100 Subject: [PATCH] Edits to tibbles + relational data (#947) * Make x known so ex.s are easy to follow + add pull * Add alt text to diagrams * Table -> data frame --- relational-data.Rmd | 134 ++++++++++++++++++++++---------------------- tibble.Rmd | 13 ++++- 2 files changed, 79 insertions(+), 68 deletions(-) diff --git a/relational-data.Rmd b/relational-data.Rmd index 4699e02..0f0ca04 100644 --- a/relational-data.Rmd +++ b/relational-data.Rmd @@ -2,27 +2,29 @@ ## Introduction -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 important. +It's rare that a data analysis involves only a single data frame. +Typically you have many data frames, and you must combine them to answer the questions that you're interested in. +Collectively, multiple data frames are called **relational data** because it is the relations, not just the individual datasets, that are important. -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! -This is needed if, for example, you have a table of people, and each person has a reference to their parents. +Relations are always defined between a pair of data frames. +All other relations are built up from this simple idea: the relations of three or more data frames are always a property of the relations between each pair. +Sometimes both elements of a pair can be the same data frame! +This is needed if, for example, you have a data frame of people, and each person has a reference to their parents. -To work with relational data you need verbs that work with pairs of tables. +To work with relational data you need verbs that work with pairs of data frames. There are three families of verbs designed to work with relational data: - **Mutating joins**, which add new variables to one data frame from matching observations in another. -- **Filtering joins**, which filter observations from one data frame based on whether or not they match an observation in the other table. +- **Filtering joins**, which filter observations from one data frame based on whether or not they match an observation in the other data frame. - **Set operations**, which treat observations as if they were set elements. The most common place to find relational data is in a *relational* database management system (or RDBMS), 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 a little different. +One other major terminology difference between databases and R is that what we generally refer to as data frames in R while the same concept is referred to as "table" in databases. +Hence you'll see references to one-table and two-table verbs in dplyr documentation. Generally, dplyr is a little easier to use than SQL because dplyr is specialised to do data analysis: it makes common data analysis operations easier, at the expense of making it more difficult to do other things that aren't commonly needed for data analysis. ### Prerequisites @@ -37,7 +39,7 @@ library(nycflights13) ## nycflights13 {#nycflights13-relational} We will use the nycflights13 package to learn about relational data. -nycflights13 contains five tibbles : `airlines`, `airports`, `weather` and `planes` which are all related to the `flights` table that you used in [data transformation]: +nycflights13 contains five tibbles : `airlines`, `airports`, `weather` and `planes` which are all related to the `flights` data frame that you used in Chapter \@ref(data-transform) on data transformation: - `airlines` lets you look up the full carrier name from its abbreviated code: @@ -63,15 +65,15 @@ nycflights13 contains five tibbles : `airlines`, `airports`, `weather` and `plan weather ``` -One way to show the relationships between the different tables is with a drawing: +One way to show the relationships between the different data frames is with a diagram: -```{r, echo = FALSE} +```{r, echo = FALSE, fig.alt = "Diagram of the relationships between airports, planes, flights, weather, and airlines datasets from the nycflights13 package. The faa variable in the airports data frame is connected to the origin and dest variables in the flights data frame. The tailnum variable in the planes data frame is connected to the tailnum variable in flights. The year, month, day, hour, and origin variables are connected to the variables with the same name in the flights data frame. And finally the carrier variables in the airlines data frame is connected to the carrier variable in the flights data frame. There are no direct connections between airports, planes, airlines, and weather data frames."} knitr::include_graphics("diagrams/relational-nycflights.png") ``` This diagram is a little overwhelming, but 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 to understand the chain of relations between the tables that you are interested in. +The key to understanding diagrams like this is to remember each relation always concerns a pair of data frames. +You don't need to understand the whole thing; you just need to understand the chain of relations between the data frames that you are interested in. For nycflights13: @@ -87,7 +89,7 @@ For nycflights13: 1. Imagine you wanted to draw (approximately) the route each plane flies from its origin to its destination. What variables would you need? - What tables would you need to combine? + What data frames would you need to combine? 2. I forgot to draw the relationship between `weather` and `airports`. What is the relationship and how should it appear in the diagram? @@ -97,7 +99,7 @@ For nycflights13: ## Keys -The variables used to connect each pair of tables are called **keys**. +The variables used to connect each pair of data frames 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`. @@ -106,16 +108,16 @@ For example, to identify an observation in `weather` you need five variables: `y 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 in the `planes` table. +- A **primary key** uniquely identifies an observation in its own data frame. + For example, `planes$tailnum` is a primary key because it uniquely identifies each plane in the `planes` data frame. -- A **foreign key** uniquely identifies an observation in another table. - For example, `flights$tailnum` is a foreign key because it appears in the `flights` table where it matches each flight to a unique plane. +- A **foreign key** uniquely identifies an observation in another data frame. + For example, `flights$tailnum` is a foreign key because it appears in the `flights` data frame where it matches each flight to a unique plane. A variable can be both a primary key *and* a foreign key. -For example, `origin` is part of the `weather` primary key, and is also a foreign key for the `airports` table. +For example, `origin` is part of the `weather` primary key, and is also a foreign key for the `airports` data frame. -Once you've identified the primary keys in your tables, it's good practice to verify that they do indeed uniquely identify each observation. +Once you've identified the primary keys in your data frames, it's good practice to verify that they do indeed uniquely identify each observation. One way to do that is to `count()` the primary keys and look for entries where `n` is greater than one: ```{r} @@ -128,8 +130,8 @@ weather %>% filter(n > 1) ``` -Sometimes a table doesn'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? +Sometimes a data frame doesn'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` data frame? You might think it would be the date plus the flight or tail number, but neither of those are unique: ```{r} @@ -144,11 +146,11 @@ flights %>% When starting to work with this data, I had naively assumed that each flight number would be only used once per day: that would make it much easier to communicate problems with a specific flight. Unfortunately that is not the case! -If a table lacks a primary key, it's sometimes useful to add one with `mutate()` and `row_number()`. +If a data frame lacks a primary key, it's sometimes useful to add one with `mutate()` and `row_number()`. That makes it easier to match observations if you've done some filtering and want to check back in with the original data. This is called a **surrogate key**. -A primary key and the corresponding foreign key in another table form a **relation**. +A primary key and the corresponding foreign key in another data frame 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 occasionally see a 1-to-1 relationship. @@ -162,12 +164,12 @@ For example, in this data there's a many-to-many relationship between airlines a 2. We know that some days of the year are "special", and fewer people than usual fly on them. How might you represent that data as a data frame? - What would be the primary keys of that table? - How would it connect to the existing tables? + What would be the primary keys of that data frame? + How would it connect to the existing data frames? 3. Identify the keys in the following datasets - a. `Lahman::Batting`, + a. `Lahman::Batting` b. `babynames::babynames` c. `nasaweather::atmos` d. `fueleconomy::vehicles` @@ -175,16 +177,16 @@ For example, in this data there's a many-to-many relationship between airlines a (You might need to install some packages and read some documentation.) -4. Draw a diagram illustrating the connections between the `Batting`, `People`, and `Salaries` tables in the Lahman package. +4. Draw a diagram illustrating the connections between the `Batting`, `People`, and `Salaries` data frames in the Lahman package. Draw another diagram that shows the relationship between `People`, `Managers`, `AwardsManagers`. - How would you characterise the relationship between the `Batting`, `Pitching`, and `Fielding` tables? + How would you characterise the relationship between the `Batting`, `Pitching`, and `Fielding` data frames? ## 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. +The first tool we'll look at for combining a pair of data frames is the **mutating join**. +A mutating join 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 `mutate()`, the join functions add variables to the right, so if you have a lot of variables already, the new variables won't get printed out. For these examples, we'll make it easier to see what's going on in the examples by creating a narrower dataset: @@ -228,7 +230,7 @@ Finally, you'll learn how to tell dplyr which variables are the keys for a given To help you learn how joins work, I'm going to use a visual representation: -```{r, echo = FALSE, out.width = NULL} +```{r, echo = FALSE, out.width = NULL, fig.alt = "x and y are two data frames with 2 columns and 3 rows each. The first column in each is the key and the second is the value. The contents of these data frames are given in the subsequent code chunk."} knitr::include_graphics("diagrams/join-setup.png") ``` @@ -247,14 +249,14 @@ y <- tribble( ) ``` -The coloured column represents the "key" variable: these are used to match the rows between the tables. +The coloured column represents the "key" variable: these are used to match the rows between the data frames. The grey column represents the "value" column that is carried along for the ride. In these examples I'll show a single key variable, but the idea generalises in a straightforward way to multiple keys and multiple values. A join is a way of connecting each row in `x` to zero, one, or more rows in `y`. The following diagram shows each potential match as an intersection of a pair of lines. -```{r, echo = FALSE, out.width = NULL} +```{r, echo = FALSE, out.width = NULL, fig.alt = "x and y data frames placed next to each other. with the key variable moved up front in y so that the key variable in x and key variable in y appear next to each other."} knitr::include_graphics("diagrams/join-setup2.png") ``` @@ -263,7 +265,7 @@ knitr::include_graphics("diagrams/join-setup2.png") In an actual join, matches will be indicated with dots. The number of dots = the number of matches = the number of rows in the output. -```{r, echo = FALSE, out.width = NULL} +```{r join-inner, echo = FALSE, out.width = NULL, fig.alt = "Keys 1 and 2 in x and y data frames are matched and indicated with lines joining these rows with dot in the middle. Hence, there are two dots in this diagram. The resulting joined data frame has two rows and 3 columns: key, val_x, and val_y. Values in the key column are 1 and 2 (the matched values)."} knitr::include_graphics("diagrams/join-inner.png") ``` @@ -272,7 +274,7 @@ knitr::include_graphics("diagrams/join-inner.png") The simplest type of join is the **inner join**. An inner join matches pairs of observations whenever their keys are equal: -```{r, echo = FALSE, out.width = NULL} +```{r, echo = FALSE, ref.label = "join-inner", opts.label = TRUE} knitr::include_graphics("diagrams/join-inner.png") ``` @@ -291,34 +293,34 @@ This means that generally inner joins are usually not appropriate for use in ana ### Outer joins {#outer-join} -An inner join keeps observations that appear in both tables. -An **outer join** keeps observations that appear in at least one of the tables. +An inner join keeps observations that appear in both data frames. +An **outer join** keeps observations that appear in at least one of the data frames. There are three types of outer joins: - A **left join** keeps all observations in `x`. - A **right join** keeps all observations in `y`. - A **full join** keeps all observations in `x` and `y`. -These joins work by adding an additional "virtual" observation to each table. +These joins work by adding an additional "virtual" observation to each data frame. This observation has a key that always matches (if no other key matches), and a value filled with `NA`. Graphically, that looks like: -```{r, echo = FALSE, out.width = NULL} +```{r, echo = FALSE, out.width = NULL, fig.alt = "Three diagrams for left, right, and full joins. In each diagram data frame x is on the left and y is on the right. The result of the join is always a data frame with three columns (key, val_x, and val_y). Left join: keys 1 and 2 from x are matched to those in y, key 3 is also carried along to the joined result since it's on the left data frame, but key 4 from y is not carried along since it's on the right but not on the left. The result is a data frame with 3 rows: keys 1, 2, and 3, all values from val_x, and the corresponding values from val_y for keys 1 and 2 with an NA for key 3, val_y. Right join: keys 1 and 2 from x are matched to those in y, key 4 is also carried along to the joined result since it's on the right data frame, but key 3 from x is not carried along since it's on the left but not on the right. The result is a data frame with 3 rows: keys 1, 2, and 4, all values from val_y, and the corresponding values from val_x for keys 1 and 2 with an NA for key 4, val_x. Full join: The resulting data frame 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 aren't present in their respective data frames."} knitr::include_graphics("diagrams/join-outer.png") ``` -The most commonly used join is the left join: you use this whenever you look up additional data from another table, because it preserves the original observations even when there isn't a match. +The most commonly used join is the left join: you use this whenever you look up additional data from another data frame, because it preserves the original observations even when there isn't a match. The left join should be your default join: use it unless you have a strong reason to prefer one of the others. Another way to depict the different types of joins is with a Venn diagram: -```{r, echo = FALSE, out.width = NULL} +```{r, echo = FALSE, out.width = NULL, fig.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. Inner join: Only intersection is shaded. Full join: Everything is shaded. Left join: Only x is shaded, but not the area in y that doesn't intersect with x. Right join: Only y is shaded, but not the area in x that doesn't intersect with y."} 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. +It might jog your memory about which join preserves the observations in which data frame, 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} @@ -327,10 +329,10 @@ But that's not always the case. This section explains what happens when the keys are not unique. There are two possibilities: -1. One table has duplicate keys. +1. One data frame has duplicate keys. This is useful when you want to add in additional information as there is typically a one-to-many relationship. - ```{r, echo = FALSE, out.width = NULL} + ```{r, echo = FALSE, out.width = NULL, fig.alt = "Diagram describing a left join where one of the data frames (x) has duplicate keys. Data frame x is on the left, has 4 rows and 2 columns (key, val_x), and has the keys 1, 2, 2, and 1. Data frame y is on the right, has 2 rows and 2 columns (key, val_y), and has the keys 1 and 2. Left joining these two data frames yields a data frame with 4 rows (keys 1, 2, 2, and 1) and 3 columns (val_x, key, val_y). All values from x$val_x are carried along, values in y for key 1 and 2 are duplicated."} knitr::include_graphics("diagrams/join-one-to-many.png") ``` @@ -353,11 +355,11 @@ There are two possibilities: left_join(x, y, by = "key") ``` -2. Both tables have duplicate keys. - This is usually an error because in neither table do the keys uniquely identify an observation. +2. Both data frames have duplicate keys. + This is usually an error because in neither data frame 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 = NULL} + ```{r, echo = FALSE, out.width = NULL, fig.alt = "Diagram describing a left join where both data frames (x and y) have duplicate keys. Data frame x is on the left, has 4 rows and 2 columns (key, val_x), and has the keys 1, 2, 2, and 3. Data frame y is on the right, has 4 rows and 2 columns (key, val_y), and has the keys 1, 2, 2, and 3 as well. Left joining these two data frames yields a data frame with 6 rows (keys 1, 2, 2, 2, 2, and 3) and 3 columns (key, val_x, val_y). All values from both datasets are included."} knitr::include_graphics("diagrams/join-many-to-many.png") ``` @@ -381,12 +383,12 @@ There are two possibilities: ### 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. +So far, the pairs of data frames have always been joined by a single variable, and that variable has the same name in both data frames. That constraint was encoded by `by = "key"`. -You can use other values for `by` to connect the tables in other ways: +You can use other values for `by` to connect the data frames in other ways: -- The default, `by = NULL`, uses all variables that appear in both tables, the so called **natural** join. - For example, the flights and weather tables match on their common variables: `year`, `month`, `day`, `hour` and `origin`. +- The default, `by = NULL`, uses all variables that appear in both data frames, the so called **natural** join. + For example, the flights and weather data frames match on their common variables: `year`, `month`, `day`, `hour` and `origin`. ```{r} flights2 %>% @@ -405,7 +407,7 @@ You can use other values for `by` to connect the tables in other ways: Note that the `year` variables (which appear in both input data frames, but are not constrained to be equal) are disambiguated in the output with a suffix. - A named character vector: `by = c("a" = "b")`. - This will match variable `a` in table `x` to variable `b` in table `y`. + This will match variable `a` in data frame `x` to variable `b` in data frame `y`. The variables from `x` will be used in the output. For example, if we want to draw a map we need to combine the flights data with the airports data which contains the location (`lat` and `lon`) of each airport. @@ -484,8 +486,8 @@ SQL is the inspiration for dplyr's conventions, so the translation is straightfo Note that "INNER" and "OUTER" are optional, and often omitted. -Joining different variables between the tables, e.g. `inner_join(x, y, by = c("a" = "b"))` uses a slightly different syntax in SQL: `SELECT * FROM x INNER JOIN y ON x.a = y.b`. -As this syntax suggests, SQL supports a wider range of join types than dplyr because you can connect the tables using constraints other than equality (sometimes called non-equijoins). +Joining different variables between the data frames, e.g. `inner_join(x, y, by = c("a" = "b"))` uses a slightly different syntax in SQL: `SELECT * FROM x INNER JOIN y ON x.a = y.b`. +As this syntax suggests, SQL supports a wider range of join types than dplyr because you can connect the data frames using constraints other than equality (sometimes called non-equijoins). ## Filtering joins {#filtering-joins} @@ -495,7 +497,7 @@ There are two types: - `semi_join(x, y)` **keeps** all observations in `x` that have a match in `y`. - `anti_join(x, y)` **drops** all observations in `x` that have a match in `y`. -Semi-joins are useful for matching filtered summary tables back to the original rows. +Semi-joins are useful for matching filtered summary data frames back to the original rows. For example, imagine you've found the top ten most popular destinations: ```{r} @@ -517,7 +519,7 @@ But it's difficult to extend that approach to multiple variables. For example, imagine that you'd found the 10 days with highest average delays. How would you construct the filter statement that used `year`, `month`, and `day` to match it back to `flights`? -Instead you can use a semi-join, which connects the two tables like a mutating join, but instead of adding new columns, only keeps the rows in `x` that have a match in `y`: +Instead you can use a semi-join, which connects the two data frames like a mutating join, but instead of adding new columns, only keeps the rows in `x` that have a match in `y`: ```{r} flights %>% @@ -526,21 +528,21 @@ flights %>% Graphically, a semi-join looks like this: -```{r, echo = FALSE, out.width = NULL} +```{r, echo = FALSE, out.width = NULL, fig.alt = "Diagram of a semi join. Data frame x is on the left and has two columns (key and val_x) with keys 1, 2, and 3. Diagram y is on the right and also has two columns (key and val_y) with keys 1, 2, and 4. Semi joining these two results in a data frame with two rows and two columns (key and val_x), with keys 1 and 2 (the only keys that match between the two data frames)."} knitr::include_graphics("diagrams/join-semi.png") ``` Only the existence of a match is important; it doesn't matter which observation is matched. This means that filtering joins never duplicate rows like mutating joins do: -```{r, echo = FALSE, out.width = NULL} +```{r, echo = FALSE, out.width = NULL, fig.alt = "Diagram of a semi join with data frames with duplicated keys. Data frame x is on the left and has two columns (key and val_x) with keys 1, 2, 2, and 3. Diagram y is on the right and also has two columns (key and val_y) with keys 1, 2, 2, and 3 as well. Semi joining these two results in a data frame with four rows and two columns (key and val_x), with keys 1, 2, 2, and 3 (the matching keys, each appearing as many times as they do in x)."} knitr::include_graphics("diagrams/join-semi-many.png") ``` The inverse of a semi-join is an anti-join. An anti-join keeps the rows that *don't* have a match: -```{r, echo = FALSE, out.width = NULL} +```{r, echo = FALSE, out.width = NULL, fig.alt = "Diagram of an anti join. Data frame x is on the left and has two columns (key and val_x) with keys 1, 2, and 3. Diagram y is on the right and also has two columns (key and val_y) with keys 1, 2, and 4. Anti joining these two results in a data frame with one row and two columns (key and val_x), with keys 3 only (the only key in x that is not in y)."} knitr::include_graphics("diagrams/join-anti.png") ``` @@ -578,7 +580,7 @@ flights %>% The data you've been working with in this chapter has been cleaned up so that you'll have as few problems as possible. Your own data is unlikely to be so nice, so there are a few things that you should do with your own data to make your joins go smoothly. -1. Start by identifying the variables that form the primary key in each table. +1. Start by identifying the variables that form the primary key in each data frame. You should usually do this based on your understanding of the data, not empirically by looking for a combination of variables that give a unique identifier. If you just look for variables without thinking about what they mean, you might get (un)lucky and find a combination that's unique in your current data but the relationship might not be true in general. @@ -591,7 +593,7 @@ Your own data is unlikely to be so nice, so there are a few things that you shou 2. Check that none of the variables in the primary key are missing. If a value is missing then it can't identify an observation! -3. Check that your foreign keys match primary keys in another table. +3. Check that your foreign keys match primary keys in another data frame. The best way to do this is with an `anti_join()`. It's common for keys not to match because of data entry errors. Fixing these is often a lot of work. @@ -599,7 +601,7 @@ Your own data is unlikely to be so nice, so there are a few things that you shou If you do have missing keys, you'll need to be thoughtful about your use of inner vs. outer joins, carefully considering whether or not you want to drop rows that don't have a match. Be aware that simply checking the number of rows before and after the join is not sufficient to ensure that your join has gone smoothly. -If you have an inner join with duplicate keys in both tables, you might get unlucky as the number of dropped rows might exactly equal the number of duplicated rows! +If you have an inner join with duplicate keys in both data frames, you might get unlucky as the number of dropped rows might exactly equal the number of duplicated rows! ## Set operations {#set-operations} diff --git a/tibble.Rmd b/tibble.Rmd index 92bf716..8fc7d03 100644 --- a/tibble.Rmd +++ b/tibble.Rmd @@ -129,8 +129,9 @@ If you want to pull out a single variable, you need some new tools, `$` and `[[` ```{r} df <- tibble( - x = runif(5), - y = rnorm(5) + id = LETTERS[1:5], + x = 1:5, + y = 6:10 ) # Extract by name @@ -148,6 +149,14 @@ df %>% .$x df %>% .[["x"]] ``` +Alternatively, you can use the `pull()` function that is specifically designed to extract a variable from a data frame. +`pull()` also takes an optional `name` argument that specifies the column to be used as names for a named vector. + +```{r} +df %>% pull(x) +df %>% pull(x, name = id) +``` + Compared to a `data.frame`, tibbles are more strict: they never do partial matching, and they will generate a warning if the column you are trying to access does not exist. ## Interacting with older code