CPP 526: Foundations of Data Science I


This lab demonstrates the process of joining two datasets through a merge() function. This is one of the most common and most important processes in data science, because it allows you to combine multiple datasets to link observations that pertain to the same individuals / cases. The deepest insights often come from bringing data together in this way.

We will use the following packages for the lab:

library( dplyr )

You can create a new R Markdown file, or download the LAB-06 RMD template:



Overview of Joins


Inner, Outer, Left and Right

There are two things to remember when conducting joins. The first is that when you merge two datasets it is rare for them both to contain the exact same observations. As a result, you need to make decisions about which data to keep and which data to drop post-merge. There are four options:

  • Keep everything: “Outer Join”
  • Keep only observations in both datasets: “Inner Join”
  • Keep all observations from dat1: “Left Join”
  • Keep all observations from dat2: “Right Join”



These options are specified through the all=, all.x=, and all.y= arguments in the merge() function, where the arguments all.x stands for observations in dat1, and all.y stands for observations in dat2 in this example.





And the equivalent operations in dplyr:



Compound IDs

It is often the case where a single ID does not unique specify observations needed to join data. For example, if you are looking at the relationship between employee eye color and their height, these are both variables that can only have one value per employee, so the employee ID would be sufficient to merge the eye color and height datasets.

If we want to look at the relationship between employee sick days in a given year and their performance, we now might have multiple years of data for each employee. To merge these two datasets we need to use both ID and YEAR. This is an example of a compound ID - two or more variables are needed to create a unique key for the join.

Consider an example where sales representatives get a bonus if they sell over $10,000 in subscriptions each year. We have one database generated by the sales department, and another generated by HR. We want to merge them to ensure bonuses have been properly issued. The data tables are structured as follows:

id year sales
A 2001 54000
A 2002 119000
B 2001 141000
B 2002 102000
C 2001 66000
C 2002 68000
id year bonus
A 2001 $0
A 2002 $10,000
B 2001 $10,000
B 2002 $10,000
C 2001 $0
C 2002 $0

The RIGHT way to merge these tables is to specify the set of IDs that allow you to indentify unique observations. The employee ID is not sufficient in this case because there are separate observations for each year. As a result,

merge( dat1, dat2, by=c("id","year") )         %>% pander()
id year sales bonus
A 2001 54000 $0
A 2002 119000 $10,000
B 2001 141000 $10,000
B 2002 102000 $10,000
C 2001 66000 $0
C 2002 68000 $0

The WRONG way to merge these two datasets is to use only the employee ID. In this case, since the rows are now no longer unique, the only choice the merge() function has is to join EVERY instance on the right to each instance on the left. It has the effect of blowing up the size of the database (notice we have increased from 6 to 12 rows), as well as duplicating fields and incorrectly aligning data.

Row number 2, for example, reports that employee A received a bonus on $54,000 in sales.

merge( dat1, dat2, by="id" )         %>% pander()
id year.x sales year.y bonus
A 2001 54000 2001 $0
A 2001 54000 2002 $10,000
A 2002 119000 2001 $0
A 2002 119000 2002 $10,000
B 2001 141000 2001 $10,000
B 2001 141000 2002 $10,000
B 2002 102000 2001 $10,000
B 2002 102000 2002 $10,000
C 2001 66000 2001 $0
C 2001 66000 2002 $0
C 2002 68000 2001 $0
C 2002 68000 2002 $0

The solution is to ensure you are using the combination of keys that ensures each observation is correctly specified.



Merge Keys

Your “keys” are the shared IDs across your datasets used for the join. You can check for shared variable names by looking at the intersection of column names in both datasets:

intersect( names(dat1), names(dat2) )
## [1] "id"   "year"

This works when the datasets were generated from a common system that uses standardized and identical ID names. In other cases, the same key may be spelled differently (‘year’ vs. ‘YEAR’) or have completely different names.

The check above at least allows you to catch instances where variable names would be repeated, and thus duplicated in the merged file. When this happens, like the ‘year’ variable in the example above, the merge operation will add an ‘x’ and ‘y’ to the end of the variable names to specify which dataset they originated from (‘year.x’ and ‘year.y’ in the example above).

In instances where variable names differ, you can specify the names directly using “by.x=” and “by.y=”:

merge( dat1, dat2, by.x="fips", by.y="FIPS" ) 



In Summary

You will be using the merge() function in this lab to join datasets. You need to specify two arguments in each merge call.

merge( dat1, dat2, by="", all="" )

Your IDs used to join dataset:

  • Use “by=” when variable names are identical
  • Use “by.x=” and “by.y=” when the variable names are spelled differently
  • Remember the c() when you have a compound key: by=c(“FIPS”,“YEAR”)

Specify an outer, inner, left, or right join:

  • all=TRUE creates an outer join
  • all=FALSE creates an inner join
  • all.x=TRUE creates a left join
  • all.y=TRUE creates a right join



Data

This week’s lab uses the Lahman baseball dataset.

library( Lahman )
data( People )
data( Batting )
data( Salaries )
data( Teams )

We are interested in identifying the teams that have achieved the largest number of wins on the smallest budgets. Who are the teams that have far outperformed their resource constraints?

This analysis requires us to link two tables from Lahman - the Salaries table for pay, and the Teams table for total wins per season. Our outcome of interest will be the cost of each win that a team earns in a season.

If we are comparing salaries across several decades, it is important to adjust salaries for inflation so that everything is in 2016 dollars. For simplicity sake we are assuming steady 3% inflation each year since 1985. Tranform the raw numbers and save the variable as salary.adj.

# adjust old salaries for inflation
# to convert all salaries into 2016 dollars
# assuming a 3 percent inflation each year 
Salaries <- 
  Salaries %>% 
  mutate( salary.adj = salary*(1.03)^( max(yearID) - yearID ) )

head( Salaries ) %>% pander()
yearID teamID lgID playerID salary salary.adj
1985 ATL NL barkele01 870000 2175070
1985 ATL NL bedrost01 550000 1375044
1985 ATL NL benedbr01 545000 1362544
1985 ATL NL campri01 633333 1583383
1985 ATL NL ceronri01 625000 1562550
1985 ATL NL chambch01 8e+05 2e+06

Total wins for each season are reported in the Teams table:

head( Teams ) %>% pander()
Table continues below
yearID lgID teamID franchID divID Rank G Ghome W L
1871 NA BS1 BNA NA 3 31 NA 20 10
1871 NA CH1 CNA NA 2 28 NA 19 9
1871 NA CL1 CFC NA 8 29 NA 10 19
1871 NA FW1 KEK NA 7 19 NA 7 12
1871 NA NY2 NNA NA 5 33 NA 16 17
1871 NA PH1 PNA NA 1 28 NA 21 7
Table continues below
DivWin WCWin LgWin WSWin R AB H X2B X3B HR BB SO
NA NA N NA 401 1372 426 70 37 3 60 19
NA NA N NA 302 1196 323 52 21 10 60 22
NA NA N NA 249 1186 328 35 40 7 26 25
NA NA N NA 137 746 178 19 8 2 33 9
NA NA N NA 302 1404 403 43 21 1 33 15
NA NA Y NA 376 1281 410 66 27 9 46 23
Table continues below
SB CS HBP SF RA ER ERA CG SHO SV IPouts HA HRA
73 16 NA NA 303 109 3.55 22 1 3 828 367 2
69 21 NA NA 241 77 2.76 25 0 1 753 308 6
18 8 NA NA 341 116 4.11 23 0 0 762 346 13
16 4 NA NA 243 97 5.17 19 1 0 507 261 5
46 15 NA NA 313 121 3.72 32 1 0 879 373 7
56 12 NA NA 266 137 4.95 27 0 0 747 329 3
Table continues below
BBA SOA E DP FP name
42 23 243 24 0.834 Boston Red Stockings
28 22 229 16 0.829 Chicago White Stockings
53 34 234 15 0.818 Cleveland Forest Citys
21 17 163 8 0.803 Fort Wayne Kekiongas
42 22 235 14 0.84 New York Mutuals
53 16 194 13 0.845 Philadelphia Athletics
Table continues below
park attendance BPF PPF teamIDBR
South End Grounds I NA 103 98 BOS
Union Base-Ball Grounds NA 104 102 CHI
National Association Grounds NA 96 100 CLE
Hamilton Field NA 101 107 KEK
Union Grounds (Brooklyn) NA 90 88 NYU
Jefferson Street Grounds NA 102 98 ATH
teamIDlahman45 teamIDretro
BS1 BS1
CH1 CH1
CL1 CL1
FW1 FW1
NY2 NY2
PH1 PH1

Note that the Salaries table records data using people as the unit of analysis, and Teams records data using teams as the unit of analysis. In order to merge these tables you will first need to convert people salaries into aggregate team salaries or team budgets.

Follow these steps to build your dataset:

  1. Aggregate salaries by team and year into a total salaries variable (group_by + summarize).
  2. Include a count of players per team each season.
  3. Merge the Teams dataset with your new team salaries table using both teamID and yearID as unique keys.
  4. Create a new variable that measures the cost of each win for each team, by season.
  5. Filter the results to retain only teams that have at least 25 teams on their roster each year.
  6. Sort your list and report the teams with the lowest cost per win.

Your table will look something like this (this table not sorted to show the moneyball teams).

Notes:


If you are interested in some of the actual math behind Moneyball (“Sabermetrics”) that breaks open the black box of each season to figure out what types of players to recruit to maximize wins, you should check out this nice blog or this R book on baseball statistics.



How to Submit

Use the following instructions to submit your assignment, which may vary depending on your course’s platform.


Knitting to HTML

When you have completed your assignment, click the “Knit” button to render your .RMD file into a .HTML report.


Special Instructions

Perform the following depending on your course’s platform:

  • Canvas: Upload both your .RMD and .HTML files to the appropriate link
  • Blackboard or iCollege: Compress your .RMD and .HTML files in a .ZIP file and upload to the appropriate link

.HTML files are preferred but not allowed by all platforms.


Before You Submit

Remember to ensure the following before submitting your assignment.

  1. Name your files using this format: Lab-##-LastName.rmd and Lab-##-LastName.html
  2. Show both the solution for your code and write out your answers in the body text
  3. Do not show excessive output; truncate your output, e.g. with function head()
  4. Follow appropriate styling conventions, e.g. spaces after commas, etc.
  5. Above all, ensure that your conventions are consistent

See Google’s R Style Guide for examples of common conventions.



Common Knitting Issues

.RMD files are knit into .HTML and other formats procedural, or line-by-line.

  • An error in code when knitting will halt the process; error messages will tell you the specific line with the error
  • Certain functions like install.packages() or setwd() are bound to cause errors in knitting
  • Altering a dataset or variable in one chunk will affect their use in all later chunks
  • If an object is “not found”, make sure it was created or loaded with library() in a previous chunk

If All Else Fails: If you cannot determine and fix the errors in a code chunk that’s preventing you from knitting your document, add eval = FALSE inside the brackets of {r} at the beginning of a chunk to ensure that R does not attempt to evaluate it, that is: {r eval = FALSE}. This will prevent an erroneous chunk of code from halting the knitting process.