Home > Articles

This chapter is from the book

14.2 Joins

Data do not always come so nicely aligned for combing using cbind and need to be joined together using a common key. This concept should be familiar to SQL users. Joins in R are not as flexible as SQL joins, but are still an essential operation in the data analysis process.

The three most commonly used functions for joins are merge in base R, join in plyr and the merging functionality in data.table. Each has pros and cons with some pros outweighing their respective cons.

To illustrate these functions we have prepared data originally made available as part of the USAID Open Government initiative.1 The data have been chopped into eight separate files so that they can be joined together. They are all available in a zip file at http://jaredlander.com/data/US_Foreign_Aid.zip. These should be downloaded and unzipped to a folder on our computer. This can be done a number of ways (including using a mouse!) but we show how to download and unzip using R.

> download.file(url="http://jaredlander.com/data/US_Foreign_Aid.zip",
+              destfile="data/ForeignAid.zip")
> unzip("data/ForeignAid.zip", exdir="data")

To load all of these files programatically, we utilize a for loop as seen in Section 10.1. We get a list of the files using dir, and then loop through that list, assigning each dataset to a name specified using assign. The function str_sub extracts individual characters from a character vector and is explained in Section 16.3.

> library(stringr)
> # first get a list of the files
> theFiles <- dir("data/", pattern="\\.csv")
> ## loop through those files
> for(a in theFiles)
+ {
+     # build a good name to assign to the data
+     nameToUse <- str_sub(string=a, start=12, end=18)
+     # read in the csv using read.table
+     # file.path is a convenient way to specify a folder and file name
+     temp <- read.table(file=file.path("data", a),
+                        header=TRUE, sep=",", stringsAsFactors=FALSE)
+     # assign them into the workspace
+     assign(x=nameToUse, value=temp)
+ }

14.2.1 merge

R comes with a built-in function, called merge, to merge two data.frames.

> Aid90s00s <- merge(x=Aid_90s, y=Aid_00s,
+                    by.x=c("Country.Name", "Program.Name"),
+                    by.y=c("Country.Name", "Program.Name"))
> head(Aid90s00s)

  Country.Name                                      Program.Name
1  Afghanistan                         Child Survival and Health
2  Afghanistan         Department of Defense Security Assistance
3  Afghanistan                            Development Assistance
4  Afghanistan Economic Support Fund/Security Support Assistance
5  Afghanistan                                Food For Education
6  Afghanistan                  Global Health and Child Survival
  FY1990 FY1991 FY1992   FY1993  FY1994 FY1995 FY1996 FY1997 FY1998
1     NA     NA     NA       NA      NA     NA     NA     NA     NA
2     NA     NA     NA       NA      NA     NA     NA     NA     NA
3     NA     NA     NA       NA      NA     NA     NA     NA     NA
4     NA     NA     NA 14178135 2769948     NA     NA     NA     NA
5     NA     NA     NA       NA      NA     NA     NA     NA     NA
6     NA     NA     NA       NA      NA     NA     NA     NA     NA
  FY1999 FY2000  FY2001   FY2002    FY2003     FY2004     FY2005
1     NA     NA      NA  2586555  56501189   40215304   39817970
2     NA     NA      NA  2964313        NA   45635526  151334908
3     NA     NA 4110478  8762080  54538965  180539337  193598227
4     NA     NA   61144 31827014 341306822 1025522037 1157530168
5     NA     NA      NA       NA   3957312    2610006    3254408
6     NA     NA      NA       NA        NA         NA         NA
      FY2006     FY2007     FY2008     FY2009
1   40856382   72527069   28397435         NA
2  230501318  214505892  495539084  552524990
3  212648440  173134034  150529862    3675202
4 1357750249 1266653993 1400237791 1418688520
5     386891         NA         NA         NA
6         NA         NA   63064912    1764252

The by.x specifies the key column(s) in the left data.frame and by.y does the same for the right data.frame. The ability to specify different column names for each data.frame is the most useful feature of merge. The biggest drawback, however, is that merge can be much slower than the alternatives.

14.2.2 plyr join

Returning to Hadley Wickham’s plyr package, we see it includes a join function, which works similarly to merge but is much faster. The biggest drawback, though, is that the key column(s) in each table must have the same name. We use the same data used previously to illustrate.

> library(plyr)
> Aid90s00sJoin <- join(x=Aid_90s, y=Aid_00s,
+                       by=c("Country.Name", "Program.Name"))
> head(Aid90s00sJoin)

  Country.Name                                      Program.Name
1  Afghanistan                         Child Survival and Health
2  Afghanistan         Department of Defense Security Assistance
3  Afghanistan                            Development Assistance
4  Afghanistan Economic Support Fund/Security Support Assistance
5  Afghanistan                                Food For Education
6  Afghanistan                  Global Health and Child Survival
  FY1990 FY1991 FY1992   FY1993  FY1994 FY1995 FY1996 FY1997 FY1998
1     NA     NA     NA       NA      NA     NA     NA     NA     NA
2     NA     NA     NA       NA      NA     NA     NA     NA     NA
3     NA     NA     NA       NA      NA     NA     NA     NA     NA
4     NA     NA     NA 14178135 2769948     NA     NA     NA     NA
5     NA     NA     NA       NA      NA     NA     NA     NA     NA
6     NA     NA     NA       NA      NA     NA     NA     NA     NA
  FY1999 FY2000  FY2001   FY2002    FY2003     FY2004     FY2005
1     NA     NA      NA  2586555  56501189   40215304   39817970
2     NA     NA      NA  2964313        NA   45635526  151334908
3     NA     NA 4110478  8762080  54538965  180539337  193598227
4     NA     NA   61144 31827014 341306822 1025522037 1157530168
5     NA     NA      NA       NA   3957312    2610006    3254408
6     NA     NA      NA       NA        NA         NA         NA
      FY2006     FY2007     FY2008     FY2009
1   40856382   72527069   28397435         NA
2  230501318  214505892  495539084  552524990
3  212648440  173134034  150529862    3675202
4 1357750249 1266653993 1400237791 1418688520
5     386891         NA         NA         NA
6         NA         NA   63064912    1764252

join has an argument for specifying a left, right, inner or full (outer) join.

We have eight data.frames containing foreign assistance data that we would like to combine into one data.frame without hand coding each join. The best way to do this is put all the data.frames into a list, and then successively join them together using Reduce.

> # first figure out the names of the data.frames
> frameNames <- str_sub(string=theFiles, start=12, end=18)
> # build an empty list
> frameList <- vector("list", length(frameNames))
> names(frameList) <- frameNames
> # add each data.frame into the list
> for(a in frameNames)
+ {
+     frameList[[a]] <- eval(parse(text=a))
+ }

A lot happened in that section of code, so let’s go over it carefully. First we reconstructed the names of the data.frames using str_sub from Hadley Wickham’s stringr package, which is shown in more detail in Chapter 16. Then we built an empty list with as many elements as there are data.frames, in this case eight, using vector and assigning its mode to “list”. We then set appropriate names to the list.

Now that the list is built and named, we looped through it, assigning to each element the appropriate data.frame. The problem is that we have the names of the data.frames as characters but the <- operator requires a variable, not a character. So we parse and evaluate the character, which realizes the actual variable. Inspecting, we see that the list does indeed contain the appropriate data.frames.

> head(frameList[[1]])

  Country.Name                                      Program.Name
1  Afghanistan                         Child Survival and Health
2  Afghanistan         Department of Defense Security Assistance
3  Afghanistan                            Development Assistance
4  Afghanistan Economic Support Fund/Security Support Assistance
5  Afghanistan                                Food For Education
6  Afghanistan                  Global Health and Child Survival
  FY2000  FY2001   FY2002    FY2003     FY2004     FY2005     FY2006
1     NA      NA  2586555  56501189   40215304   39817970   40856382
2     NA      NA  2964313        NA   45635526  151334908  230501318
3     NA 4110478  8762080  54538965  180539337  193598227  212648440
4     NA   61144 31827014 341306822 1025522037 1157530168 1357750249
5     NA      NA       NA   3957312    2610006    3254408     386891
6     NA      NA       NA        NA         NA         NA         NA
      FY2007     FY2008     FY2009
1   72527069   28397435         NA
2  214505892  495539084  552524990
3  173134034  150529862    3675202
4 1266653993 1400237791 1418688520
5         NA         NA         NA
6         NA   63064912    1764252

> head(frameList[["Aid_00s"]])

  Country.Name                                      Program.Name
1  Afghanistan                         Child Survival and Health
2  Afghanistan         Department of Defense Security Assistance
3  Afghanistan                            Development Assistance
4  Afghanistan Economic Support Fund/Security Support Assistance
5  Afghanistan                                Food For Education
6  Afghanistan                  Global Health and Child Survival
  FY2000  FY2001   FY2002    FY2003     FY2004     FY2005     FY2006
1     NA      NA  2586555  56501189   40215304   39817970   40856382
2     NA      NA  2964313        NA   45635526  151334908  230501318
3     NA 4110478  8762080  54538965  180539337  193598227  212648440
4     NA   61144 31827014 341306822 1025522037 1157530168 1357750249
5     NA      NA       NA   3957312    2610006    3254408     386891
6     NA      NA       NA        NA         NA         NA         NA
      FY2007     FY2008     FY2009
1   72527069   28397435         NA
2  214505892  495539084  552524990
3  173134034  150529862    3675202
4 1266653993 1400237791 1418688520
5         NA         NA         NA
6         NA   63064912    1764252

> head(frameList[[5]])

  Country.Name                                      Program.Name
1  Afghanistan                         Child Survival and Health
2  Afghanistan         Department of Defense Security Assistance
3  Afghanistan                            Development Assistance
4  Afghanistan Economic Support Fund/Security Support Assistance
5  Afghanistan                                Food For Education
6  Afghanistan                  Global Health and Child Survival
  FY1960 FY1961    FY1962 FY1963 FY1964 FY1965 FY1966 FY1967 FY1968
1     NA     NA        NA     NA     NA     NA     NA     NA     NA
2     NA     NA        NA     NA     NA     NA     NA     NA     NA
3     NA     NA        NA     NA     NA     NA     NA     NA     NA
4     NA     NA 181177853     NA     NA     NA     NA     NA     NA
5     NA     NA        NA     NA     NA     NA     NA     NA     NA
6     NA     NA        NA     NA     NA     NA     NA     NA     NA
  FY1969
1     NA
2     NA
3     NA
4     NA
5     NA
6     NA

> head(frameList[["Aid_60s"]])

  Country.Name                                      Program.Name
1  Afghanistan                         Child Survival and Health
2  Afghanistan         Department of Defense Security Assistance
3  Afghanistan                            Development Assistance
4  Afghanistan Economic Support Fund/Security Support Assistance
5  Afghanistan                                Food For Education
6  Afghanistan                  Global Health and Child Survival
  FY1960 FY1961    FY1962 FY1963 FY1964 FY1965 FY1966 FY1967 FY1968
1     NA     NA        NA     NA     NA     NA     NA     NA     NA
2     NA     NA        NA     NA     NA     NA     NA     NA     NA
3     NA     NA        NA     NA     NA     NA     NA     NA     NA
4     NA     NA 181177853     NA     NA     NA     NA     NA     NA
5     NA     NA        NA     NA     NA     NA     NA     NA     NA
6     NA     NA        NA     NA     NA     NA     NA     NA     NA
  FY1969
1     NA
2     NA
3     NA
4     NA
5     NA
6     NA

Having all the data.frames in a list allows us to iterate through the list, joining all the elements together (or applying any function to the elements iteratively). Rather than using a loop, we use the Reduce function to speed up the operation.

> allAid <- Reduce(function(...){
+     join(..., by=c("Country.Name", "Program.Name"))},
+     frameList)
> dim(allAid)

[1] 2453   67

> library(useful)
> corner(allAid, c=15)

  Country.Name                                      Program.Name
1  Afghanistan                         Child Survival and Health
2  Afghanistan         Department of Defense Security Assistance
3  Afghanistan                            Development Assistance
4  Afghanistan Economic Support Fund/Security Support Assistance
5  Afghanistan                                Food For Education
  FY2000  FY2001   FY2002    FY2003     FY2004     FY2005     FY2006
1     NA      NA  2586555  56501189   40215304   39817970   40856382
2     NA      NA  2964313        NA   45635526  151334908  230501318
3     NA 4110478  8762080  54538965  180539337  193598227  212648440
4     NA   61144 31827014 341306822 1025522037 1157530168 1357750249
5     NA      NA       NA   3957312    2610006    3254408     386891
      FY2007     FY2008     FY2009     FY2010 FY1946 FY1947
1   72527069   28397435         NA         NA     NA     NA
2  214505892  495539084  552524990  316514796     NA     NA
3  173134034  150529862    3675202         NA     NA     NA
4 1266653993 1400237791 1418688520 2797488331     NA     NA
5         NA         NA         NA         NA     NA     NA

> bottomleft(allAid, c=15)

     Country.Name           Program.Name  FY2000  FY2001   FY2002
2449     Zimbabwe Other State Assistance 1341952  322842       NA
2450     Zimbabwe Other USAID Assistance 3033599 8464897  6624408
2451     Zimbabwe            Peace Corps 2140530 1150732   407834
2452     Zimbabwe                Title I      NA      NA       NA
2453     Zimbabwe               Title II      NA      NA 31019776
       FY2003   FY2004   FY2005  FY2006    FY2007    FY2008    FY2009
2449       NA   318655    44553  883546   1164632   2455592   2193057
2450 11580999 12805688 10091759 4567577  10627613  11466426  41940500
2451       NA       NA       NA      NA        NA        NA        NA
2452       NA       NA       NA      NA        NA        NA        NA
2453       NA       NA       NA  277468 100053600 180000717 174572685
       FY2010 FY1946 FY1947
2449  1605765     NA     NA
2450 30011970     NA     NA
2451       NA     NA     NA
2452       NA     NA     NA
2453 79545100     NA     NA

Reduce can be a difficult function to grasp, so we illustrate it with a simple example. Let’s say we have a vector of the first ten integers, 1:10, and want to sum them (forget for a moment that sum(1:10) will work perfectly). We can call Reduce(sum, 1:10), which will first add 1 and 2. It will then add 3 to that result, then 4 to that result and so on, resulting in 55.

Likewise, we passed a list to a function that joins its inputs, which in this case was simply ..., meaning that anything could be passed. Using ... is an advanced trick of R programming that can be difficult to get right. Reduce passed the first two data.frames in the list, which were then joined. That result was then joined to the next data.frame and so on until they were all joined together.

14.2.3 data.table merge

Like many other operations in data.table, joining data requires a different syntax, and possibly a different way of thinking. To start, we convert two of our foreign aid datasets’ data.frames into data.tables.

> library(data.table)
> dt90 <- data.table(Aid_90s, key=c("Country.Name", "Program.Name"))
> dt00 <- data.table(Aid_00s, key=c("Country.Name", "Program.Name"))

Then, doing the join is a simple operation. Note that the join requires specifying the keys for the data.tables, which we did during their creation.

> dt0090 <- dt90[dt00]

In this case dt90 is the left side, dt00 is the right side and a left join was performed.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020