October 27, 2018

In this post in the R:case4base series we will look at one of the most common operations on multiple data frames - merge, also known as JOIN in SQL terms.

R Merge – How To Merge Two R Data Frames Inspecting your data Ways to Select a Subset of Data From an R Data Frame Create an R Data Frame Sort an R Data Frame Add and Remove Columns Renaming Columns Add and Remove Rows Merge Two Data Frames.

We will learn how to do the 4 basic types of join - inner, left, right and full join with base R and show how to perform the same with tidyverse’s dplyr and data.table’s methods. A quick benchmark will also be included.

  1. This is a very tough thing to do. And i don’t a have an answer to you’re original question, however i’ve a suggestion of what you could do in order to merge you’re data sets.
  2. Concatenating datasets. At the high level, there are two ways you can merge datasets; you can add information by adding more rows or by adding more columns to your dataset. In general, when you have datasets that have the same set of columns or have the same set of observations, you can concatenate them vertically or horizontally, respectively.

To showcase the merging, we will use a very slightly modified dataset provided by Hadley Wickham’s nycflights13 package, mainly the flights and weather data frames. Let’s get right into it and simply show how to perform the different types of joins with base R.

First, we prepare the data and store the columns we will merge by (join on) into mergeCols:

Now, we show how to perform the 4 merges (joins):

Left (outer) join

Full (outer) join

The key arguments of base merge data.frame method are:

  • x, y - the 2 data frames to be merged
  • by - names of the columns to merge on. If the column names are different in the two data frames to merge, we can specify by.x and by.y with the names of the columns in the respective data frames. The by argument can also be specified by number, logical vector or left unspecified, in which case it defaults to the intersection of the names of the two data frames. From best practice perspective it is advisable to always specify the argument explicitly, ideally by column names.
  • all, all.x, all.y - default to FALSE and can be used specify the type of join we want to perform:
    • all = FALSE (the default) - gives an inner join - combines the rows in the two data frames that match on the by columns
    • all.x = TRUE - gives a left (outer) join - adds rows that are present in x, even though they do not have a matching row in y to the result for all = FALSE
    • all.y = TRUE - gives a right (outer) join - adds rows that are present in y, even though they do not have a matching row in x to the result for all = FALSE
    • all = TRUE - gives a full (outer) join. This is a shorthand for all.x = TRUE and all.y = TRUE

Other arguments include

  • sort - if TRUE (default), results are sorted on the by columns
  • suffixes - length 2 character vector, specifying the suffixes to be used for making the names of columns in the result which are not used for merging unique
  • incomparables - for single-column merging only, a vector of values that cannot be matched. Any value in x matching a value in this vector is assigned the nomatch value (which can be passed using ...)

For this example, let us have a list of all the data frames included in the nycflights13 package, slightly updated such that they can me merged with the default value for by, purely for this exercise, and store them into a list called flightsList:

Since merge is designed to work with 2 data frames, merging multiple data frames can of course be achieved by nesting the calls to merge:

We can however achieve this same goal much more elegantly, taking advantage of base R’s Reduce function:

Note that this example is oversimplified and the data was updated such that the default values for by give meaningful joins. For example, in the original planes data frame the column year would have been matched onto the year column of the flights data frame, which is nonsensical as the years have different meanings in the two data frames. This is why we renamed the year column in the planes data frame to yearmanufactured for the above example.

Using the tidyverse

The dplyr package comes with a set of very user-friendly functions that seem quite self-explanatory:

We can also use the “forward pipe” operator %>% that becomes very convenient when merging multiple data frames:

Using data.table

The data.table package provides an S3 method for the merge generic that has a very similar structure to the base method for data frames, meaning its use is very convenient for those familiar with that method. In fact the code is exactly the same as the base one for our example use.

One important difference worth noting is that the by argument is by default constructed differently with data.table.

We however provide it explicitly, therefore this difference does not directly affect our example:

Alternatively, we can write data.table joins as subsets:

For a quick overview, lets look at a basic benchmark without package loading overhead for each of the mentioned packages:

Inner join

Full (outer) join

Visualizing the results in this case shows base R comes way behind the two alternatives, even with sort = FALSE.

Note: The benchmarks are ran on a standard droplet by DigitalOcean, with 2GB of memory a 2vCPUs.

No time for reading? Click here to get just the code with commentary

  • Animated inner join, left join, right join and full join by Garrick Aden-Buie for an easier understanding
  • Joining Data in R with dplyr by Wiliam Surles
  • Join (SQL) Wikipedia page
  • The nycflights13 package on CRAN

Exactly 100 years ago tomorrow, October 28th, 1918 the independence of Czechoslovakia was proclaimed by the Czechoslovak National Council, resulting in the creation of the first democratic state of Czechs and Slovaks in history.

Did you find this post helpful or interesting? Help others find it by sharing:

13.1 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.

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.

To work with relational data you need verbs that work with pairs of tables. There are three families of verbs designed to work with relational data:

  • Mutating joins, which add new variables to one data frame from matchingobservations in another.

  • Filtering joins, which filter observations from one data frame based onwhether or not they match an observation in the other table.

  • 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. 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.

13.1.1 Prerequisites

We will explore relational data from nycflights13 using the two-table verbs from dplyr.

13.2 nycflights13

We will use the nycflights13 package to learn about relational data. nycflights13 contains four tibbles that are related to the flights table that you used in data transformation:

  • airlines lets you look up the full carrier name from its abbreviatedcode:

  • airports gives information about each airport, identified by the faaairport code:

  • planes gives information about each plane, identified by its tailnum:

  • weather gives the weather at each NYC airport for each hour:

One way to show the relationships between the different tables is with a drawing:

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.

For nycflights13:

  • flights connects to planes via a single variable, tailnum.

  • flights connects to airlines through the carrier variable.

  • flights connects to airports in two ways: via the origin anddest variables.

  • flights connects to weather via origin (the location), andyear, month, day and hour (the time).

13.2.1 Exercises

  1. Imagine you wanted to draw (approximately) the route each plane flies fromits origin to its destination. What variables would you need? What tableswould 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?

  3. weather only contains information for the origin (NYC) airports. Ifit contained weather records for all airports in the USA, what additionalrelation would it define with flights?

  4. We know that some days of the year are “special”, and fewer people thanusual 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 theexisting tables?

13.3 Keys

Left Join Multiple Datasets In R

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 identifieseach plane in the planes table.

  • A foreign key uniquely identifies an observation in another table.For example, flights$tailnum is a foreign key because it appears in theflights table 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.

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 to count() the primary keys and look for entries where n is greater than one:

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? You might think it would be the date plus the flight or tail number, but neither of those are unique:

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(). 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. 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. You can think of this as a special case of 1-to-many. You can 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 airline flies to many airports; each airport hosts many airlines.

13.3.1 Exercises

  1. Add a surrogate key to flights.

  2. Identify the keys in the following datasets

    1. Lahman::Batting,
    2. babynames::babynames
    3. nasaweather::atmos
    4. fueleconomy::vehicles

    (You might need to install some packages and read some documentation.)

  3. Draw a diagram illustrating the connections between the Batting,People, and Salaries tables in the Lahman package. Draw another diagramthat shows the relationship between People, Managers, AwardsManagers.

    How would you characterise the relationship between the Batting,Pitching, and Fielding tables?

13.4 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.

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:

(Remember, when you’re in RStudio, you can also use View() to avoid this problem.)

Imagine you want to add the full airline name to the flights2 data. You can combine the airlines and flights2 data frames with left_join():

The result of joining airlines to flights2 is an additional variable: name. This is why I call this type of join a mutating join. In this case, you could have got to the same place using mutate() and R’s base subsetting:

But this is hard to generalise when you need to match multiple variables, and takes close reading to figure out the overall intent.

The following sections explain, in detail, how mutating joins work. You’ll start by learning a useful visual representation of joins. We’ll then use that to explain the four mutating join functions: the inner join, and the three outer joins. When working with real data, keys don’t always uniquely identify observations, so next we’ll talk about what happens when there isn’t a unique match. Finally, you’ll learn how to tell dplyr which variables are the keys for a given join.

13.4.1 Understanding joins

To help you learn how joins work, I’m going to use a visual representation:

The coloured column represents the “key” variable: these are used to match the rows between the tables. 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.

(If you look closely, you might notice that we’ve switched the order of the key and value columns in x. This is to emphasise that joins match based on the key; the value is just carried along for the ride.)

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.

13.4.2 Inner join

The simplest type of join is the inner join. An inner join matches pairs of observations whenever their keys are equal:

(To be precise, this is an inner equijoin because the keys are matched using the equality operator. Since most joins are equijoins we usually drop that specification.)

The output of an inner join is a new data frame that contains the key, the x values, and the y values. We use by to tell dplyr which variable is the key:

The most important property of an inner join is that unmatched rows are not included in the result. This means that generally inner joins are usually not appropriate for use in analysis because it’s too easy to lose observations.

13.4.3 Outer joins

An inner join keeps observations that appear in both tables. An outer join keeps observations that appear in at least one of the tables. 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. This observation has a key that always matches (if no other key matches), and a value filled with NA.

Graphically, that looks like:

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 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:

Join Two Datasets In R

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.

13.4.4 Duplicate keys

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. One table has duplicate keys. This is useful when you want toadd in additional information as there is typically a one-to-manyrelationship.

    Note that I’ve put the key column in a slightly different positionin the output. This reflects that the key is a primary key in yand a foreign key in x.

  2. Both tables have duplicate keys. This is usually an error because inneither table do the keys uniquely identify an observation. When you joinduplicated keys, you get all possible combinations, the Cartesian product:

13.4.5 Defining the key columns

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:

Join Two Datasets In R
  • The default, by = NULL, uses all variables that appear in both tables,the so called natural join. For example, the flights and weather tablesmatch on their common variables: year, month, day, hour andorigin.

  • A character vector, by = 'x'. This is like a natural join, but uses onlysome of the common variables. For example, flights and planes haveyear variables, but they mean different things so we only want to join bytailnum.

    Note that the year variables (which appear in both input data frames,but are not constrained to be equal) are disambiguated in the output witha suffix.

  • A named character vector: by = c('a' = 'b'). This willmatch variable a in table x to variable b in table y. Thevariables from x will be used in the output.

    For example, if we want to draw a map we need to combine the flights datawith the airports data which contains the location (lat and lon) ofeach airport. Each flight has an origin and destination airport, so weneed to specify which one we want to join to:

13.4.6 Exercises

  1. Compute the average delay by destination, then join on the airportsdata frame so you can show the spatial distribution of delays. Here’s aneasy way to draw a map of the United States:

    (Don’t worry if you don’t understand what semi_join() does — you’lllearn about it next.)

    You might want to use the size or colour of the points to displaythe average delay for each airport.

  2. Add the location of the origin and destination (i.e. the lat and lon)to flights.

  3. Is there a relationship between the age of a plane and its delays?

  4. What weather conditions make it more likely to see a delay?

  5. What happened on June 13 2013? Display the spatial pattern of delays,and then use Google to cross-reference with the weather.

13.4.7 Other implementations

base::merge() can perform all four types of mutating join:

inner_join(x, y)merge(x, y)
left_join(x, y)merge(x, y, all.x = TRUE)
right_join(x, y)merge(x, y, all.y = TRUE),
full_join(x, y)merge(x, y, all.x = TRUE, all.y = TRUE)

The advantages of the specific dplyr verbs is that they more clearly convey the intent of your code: the difference between the joins is really important but concealed in the arguments of merge(). dplyr’s joins are considerably faster and don’t mess with the order of the rows.

SQL is the inspiration for dplyr’s conventions, so the translation is straightforward:

inner_join(x, y, by = 'z')SELECT * FROM x INNER JOIN y USING (z)
left_join(x, y, by = 'z')SELECT * FROM x LEFT OUTER JOIN y USING (z)
right_join(x, y, by = 'z')SELECT * FROM x RIGHT OUTER JOIN y USING (z)
full_join(x, y, by = 'z')SELECT * FROM x FULL OUTER JOIN y USING (z)

Note that “INNER” and “OUTER” are optional, and often omitted.

Merge Two Datasets R

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).

13.5 Filtering joins

Filtering joins match observations in the same way as mutating joins, but affect the observations, not the variables. 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. For example, imagine you’ve found the top ten most popular destinations:

Now you want to find each flight that went to one of those destinations. You could construct a filter yourself:

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:

Graphically, a semi-join looks like this:

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:

The inverse of a semi-join is an anti-join. An anti-join keeps the rows that don’t have a match:

Anti-joins are useful for diagnosing join mismatches. For example, when connecting flights and planes, you might be interested to know that there are many flights that don’t have a match in planes:

13.5.1 Exercises

  1. What does it mean for a flight to have a missing tailnum? What do thetail numbers that don’t have a matching record in planes have in common?(Hint: one variable explains ~90% of the problems.)

  2. Filter flights to only show flights with planes that have flown at least 100flights.

  3. Combine fueleconomy::vehicles and fueleconomy::common to find only therecords for the most common models.

  4. Find the 48 hours (over the course of the whole year) that have the worstdelays. Cross-reference it with the weather data. Can you see anypatterns?

  5. What does anti_join(flights, airports, by = c('dest' = 'faa')) tell you?What does anti_join(airports, flights, by = c('faa' = 'dest')) tell you?

  6. You might expect that there’s an implicit relationship between planeand airline, because each plane is flown by a single airline. Confirmor reject this hypothesis using the tools you’ve learned above.

13.6 Join problems

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.You should usually do this based on your understanding of the data, notempirically by looking for a combination of variables that give aunique identifier. If you just look for variables without thinking aboutwhat they mean, you might get (un)lucky and find a combination that’sunique in your current data but the relationship might not be true ingeneral.

    For example, the altitude and longitude uniquely identify each airport,but they are not good identifiers!

  2. Check that none of the variables in the primary key are missing. Ifa value is missing then it can’t identify an observation!

  3. Check that your foreign keys match primary keys in another table. Thebest way to do this is with an anti_join(). It’s common for keysnot to match because of data entry errors. Fixing these is often a lot ofwork.

    If you do have missing keys, you’ll need to be thoughtful about youruse of inner vs. outer joins, carefully considering whether or not youwant 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!

13.7 Set operations

The final type of two-table verb are the set operations. Generally, I use these the least frequently, but they are occasionally useful when you want to break a single complex filter into simpler pieces. All these operations work with a complete row, comparing the values of every variable. These expect the x and y inputs to have the same variables, and treat the observations like sets:

  • intersect(x, y): return only observations in both x and y.
  • union(x, y): return unique observations in x and y.
  • setdiff(x, y): return observations in x, but not in y.

Given this simple data:

The four possibilities are:

Coments are closed

Most Viewed Posts

  • Microsoft Teams Chromebook
  • Pivot Table Merge Cells
  • Sigil For Inner Peace
  • Invoice Text
  • Google Drive File Stream Logo

Scroll to top