-
Notifications
You must be signed in to change notification settings - Fork 3
/
p-076-merging-data.rmd
176 lines (107 loc) · 6.06 KB
/
p-076-merging-data.rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
---
output:
html_document:
theme: readable
highlight: tango
toc: true
toc_depth: 1
number_sections: true
self_contained: false
css: textbook.css
---
```{r, echo=F }
knitr::opts_chunk$set( echo = TRUE, message=F, warning=F, fig.width=8 )
```
# Merging Data
```{r setup, include=TRUE}
library( dplyr )
library( pander )
```
<br>
This chapter 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.
<br><br>
# Overview of Joins
<br>
## 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"
<br>
```{r, fig.cap="", echo=F, out.width='40%', fig.align='center' }
knitr::include_graphics( "figures/shared_observations.png" )
```
<br>
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.
```{r, fig.cap="", echo=F, out.width='80%', fig.align='center' }
knitr::include_graphics( "figures/outer_join.png" )
```
<br>
```{r, fig.cap="", echo=F, out.width='80%', fig.align='center'}
knitr::include_graphics( "figures/inner_join.png" )
```
<br>
```{r, fig.cap="", echo=F, out.width='80%', fig.align='center' }
knitr::include_graphics( "figures/left_join.png" )
```
<br>
```{r, fig.cap="", echo=F, out.width='80%', fig.align='center' }
knitr::include_graphics( "figures/right_join.png" )
```
<br><br>
## Compound IDs
It is often the case where a single ID does not uniquely 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.
```{r, fig.cap="", echo=F, out.width='60%', fig.align='center' }
knitr::include_graphics( "figures/compound_ids.png" )
```
Consider an example where sales representatives get a bonus if they sell over $100,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:
```{r, echo=F}
id <- c("A","A","B","B","C","C")
year <- c(2001,2002,2001,2002,2001,2002)
sales <- c(54000,119000,141000,102000,66000,68000)
bonus <- c(F,T,T,T,F,F)
dat1 <- data.frame( id, year, sales )
dat2 <- data.frame( id, year, bonus )
dat1 %>% pander()
dat2 %>% pander()
```
The RIGHT way to merge these tables is to specify the set of IDs that allow you to identify unique observations. The employee ID is not sufficient in this case because there are separate observations for each year. As a result:
```{r}
merge( dat1, dat2, by=c("id","year") ) %>% pander()
```
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.
```{r}
merge( dat1, dat2, by="id" ) %>% pander()
```
The solution is to ensure you are using the combination of keys that ensures each observation is correctly specified.
<br><br>
## 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 names in both:
```{r}
intersect( names(dat1), names(dat2) )
```
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=":
```{r, eval=F}
merge( dat1, dat2, by.x="fips", by.y="FIPS" )
```
<br><br>
## 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.
```{r, eval=F}
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
<br><br>