DS4PS


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:

You can create a new RMarkdown file, or download the lab template:

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,

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.

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:

## [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=”:



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.

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.

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.

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:

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.



Submission Instructions

After you have completed your lab, knit your RMD file. Submit your code and a printed view of your final table.

Login to Canvas at http://canvas.asu.edu and navigate to the assignments tab in the course repository. Upload your RMD and your HTML files to the appropriate lab submission link.

Remember to: