This repository has been archived by the owner on Sep 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 369
/
bit008_lookup.html
339 lines (294 loc) · 13.2 KB
/
bit008_lookup.html
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<title>Table lookup</title>
<script src="libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="libs/navigation-1.1/tabsets.js"></script>
<link href="libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="libs/highlightjs-9.12.0/highlight.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-68219208-1', 'auto');
ga('send', 'pageview');
</script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<link rel="stylesheet" href="libs/local/main.css" type="text/css" />
<link rel="stylesheet" href="libs/local/nav.css" type="text/css" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" type="text/css" />
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
height: auto;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<header>
<div class="nav">
<a class="nav-logo" href="index.html">
<img src="static/img/stat545-logo-s.png" width="70px" height="70px"/>
</a>
<ul>
<li class="home"><a href="index.html">Home</a></li>
<li class="faq"><a href="faq.html">FAQ</a></li>
<li class="syllabus"><a href="syllabus.html">Syllabus</a></li>
<li class="topics"><a href="topics.html">Topics</a></li>
<li class="people"><a href="people.html">People</a></li>
</ul>
</div>
</header>
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Table lookup</h1>
</div>
<p>I try to use <a href="bit001_dplyr-cheatsheet.html">dplyr joins</a> for most tasks that combine data from two tibbles. But sometimes you just need good old “table lookup”. Party like it’s Microsoft Excel <code>LOOKUP()</code> time!</p>
<div id="load-gapminder-and-the-tidyverse" class="section level3">
<h3>Load gapminder and the tidyverse</h3>
<pre class="r"><code>library(gapminder)
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.0.0 ✔ purrr 0.2.5
## ✔ tibble 1.4.99.9005 ✔ dplyr 0.7.7
## ✔ tidyr 0.8.1 ✔ stringr 1.3.1
## ✔ readr 1.1.1 ✔ forcats 0.3.0
## ── Conflicts ────────────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()</code></pre>
</div>
<div id="create-mini-gapminder" class="section level3">
<h3>Create mini Gapminder</h3>
<p>Work with a tiny subset of Gapminder, <code>mini_gap</code>.</p>
<pre class="r"><code>mini_gap <- gapminder %>%
filter(country %in% c("Belgium", "Canada", "United States", "Mexico"),
year > 2000) %>%
select(-pop, -gdpPercap) %>%
droplevels()
mini_gap
## # A tibble: 8 x 4
## country continent year lifeExp
## <fct> <fct> <int> <dbl>
## 1 Belgium Europe 2002 78.3
## 2 Belgium Europe 2007 79.4
## 3 Canada Americas 2002 79.8
## 4 Canada Americas 2007 80.7
## 5 Mexico Americas 2002 74.9
## 6 Mexico Americas 2007 76.2
## 7 United States Americas 2002 77.3
## 8 United States Americas 2007 78.2</code></pre>
</div>
<div id="dorky-national-food-example." class="section level3">
<h3>Dorky national food example.</h3>
<p>Make a lookup table of national foods. Or at least the stereotype. Yes I have intentionally kept Mexico in mini-Gapminder and neglected to put Mexico here.</p>
<pre class="r"><code>food <- tribble(
~ country, ~ food,
"Belgium", "waffle",
"Canada", "poutine",
"United States", "Twinkie"
)
food
## # A tibble: 3 x 2
## country food
## <chr> <chr>
## 1 Belgium waffle
## 2 Canada poutine
## 3 United States Twinkie</code></pre>
</div>
<div id="lookup-national-food" class="section level3">
<h3>Lookup national food</h3>
<p><code>match(x, table)</code> reports where the values in the key <code>x</code> appear in the lookup variable <code>table</code>. It returns positive integers for use as indices. It assumes <code>x</code> and <code>table</code> are free-range vectors, i.e. there’s no implicit data frame on the radar here.</p>
<p>Gapminder’s <code>country</code> plays the role of the key <code>x</code>. It is replicated, i.e. non-unique, in <code>mini_gap</code>, but not in <code>food</code>, i.e. no country appears more than once <code>food$country</code>. FYI <code>match()</code> actually allows for multiple matches by only consulting the first.</p>
<pre class="r"><code>match(x = mini_gap$country, table = food$country)
## [1] 1 1 2 2 NA NA 3 3</code></pre>
<p>In table lookup, there is always a value variable <code>y</code> that you plan to index with the <code>match(x, table)</code> result. It often lives together with <code>table</code> in a data frame; they should certainly be the same length and synced up with respect to row order.</p>
<p>But first …</p>
<p>I get <code>x</code> and <code>table</code> backwards some non-negligible percentage of the time. So I store the match indices and index the data frame where <code>table</code> lives with it. Add <code>x</code> as a column and eyeball-o-metrically assess that all is well.</p>
<pre class="r"><code>(indices <- match(x = mini_gap$country, table = food$country))
## [1] 1 1 2 2 NA NA 3 3
add_column(food[indices, ], x = mini_gap$country)
## # A tibble: 8 x 3
## country food x
## <chr> <chr> <fct>
## 1 Belgium waffle Belgium
## 2 Belgium waffle Belgium
## 3 Canada poutine Canada
## 4 Canada poutine Canada
## 5 <NA> <NA> Mexico
## 6 <NA> <NA> Mexico
## 7 United States Twinkie United States
## 8 United States Twinkie United States</code></pre>
<p>Once all looks good, do the actual table lookup and, possibly, add the new info to your main table.</p>
<pre class="r"><code>mini_gap %>%
mutate(food = food$food[indices])
## # A tibble: 8 x 5
## country continent year lifeExp food
## <fct> <fct> <int> <dbl> <chr>
## 1 Belgium Europe 2002 78.3 waffle
## 2 Belgium Europe 2007 79.4 waffle
## 3 Canada Americas 2002 79.8 poutine
## 4 Canada Americas 2007 80.7 poutine
## 5 Mexico Americas 2002 74.9 <NA>
## 6 Mexico Americas 2007 76.2 <NA>
## 7 United States Americas 2002 77.3 Twinkie
## 8 United States Americas 2007 78.2 Twinkie</code></pre>
<p>Of course, if this was really our exact task, we could have used a join!</p>
<pre class="r"><code>mini_gap %>%
left_join(food)
## Joining, by = "country"
## Warning: Column `country` joining factor and character vector, coercing
## into character vector
## # A tibble: 8 x 5
## country continent year lifeExp food
## <chr> <fct> <int> <dbl> <chr>
## 1 Belgium Europe 2002 78.3 waffle
## 2 Belgium Europe 2007 79.4 waffle
## 3 Canada Americas 2002 79.8 poutine
## 4 Canada Americas 2007 80.7 poutine
## 5 Mexico Americas 2002 74.9 <NA>
## 6 Mexico Americas 2007 76.2 <NA>
## 7 United States Americas 2002 77.3 Twinkie
## 8 United States Americas 2007 78.2 Twinkie</code></pre>
<p>But sometimes you have a substantive reason (or psychological hangup) that makes you prefer the table look up interface.</p>
</div>
<div id="worlds-laziest-table-lookup" class="section level3">
<h3>World’s laziest table lookup</h3>
<p>While I’m here, let’s demo another standard R trick that’s based on indexing by name.</p>
<p>Imagine the table you want to consult isn’t even a tibble but is, instead, a named character vector.</p>
<pre class="r"><code>(food_vec <- setNames(food$food, food$country))
## Belgium Canada United States
## "waffle" "poutine" "Twinkie"</code></pre>
<p>Another way to get the national foods for mini-Gapminder is to simply index <code>food_vec</code> with <code>mini_gap$country</code>.</p>
<pre class="r"><code>mini_gap %>%
mutate(food = food_vec[country])
## # A tibble: 8 x 5
## country continent year lifeExp food
## <fct> <fct> <int> <dbl> <chr>
## 1 Belgium Europe 2002 78.3 waffle
## 2 Belgium Europe 2007 79.4 waffle
## 3 Canada Americas 2002 79.8 poutine
## 4 Canada Americas 2007 80.7 poutine
## 5 Mexico Americas 2002 74.9 Twinkie
## 6 Mexico Americas 2007 76.2 Twinkie
## 7 United States Americas 2002 77.3 <NA>
## 8 United States Americas 2007 78.2 <NA></code></pre>
<p>HOLD ON. STOP. Twinkies aren’t the national food of Mexico!?! What went wrong?</p>
<p>Remember <code>mini_gap$country</code> is a factor. So when we use it in an indexing context, it’s integer nature is expressed. It is pure luck that we get the right foods for Belgium and Canada. Luckily the Mexico - United States situation tipped us off. Here’s what we are really indexing <code>food_vec</code> by above:</p>
<pre class="r"><code>unclass(mini_gap$country)
## [1] 1 1 2 2 3 3 4 4
## attr(,"levels")
## [1] "Belgium" "Canada" "Mexico" "United States"</code></pre>
<p>To get our desired result, we need to explicitly coerce <code>mini_gap$country</code> to character.</p>
<pre class="r"><code>mini_gap %>%
mutate(food = food_vec[as.character(country)])
## # A tibble: 8 x 5
## country continent year lifeExp food
## <fct> <fct> <int> <dbl> <chr>
## 1 Belgium Europe 2002 78.3 waffle
## 2 Belgium Europe 2007 79.4 waffle
## 3 Canada Americas 2002 79.8 poutine
## 4 Canada Americas 2007 80.7 poutine
## 5 Mexico Americas 2002 74.9 <NA>
## 6 Mexico Americas 2007 76.2 <NA>
## 7 United States Americas 2002 77.3 Twinkie
## 8 United States Americas 2007 78.2 Twinkie</code></pre>
<p>When your key variable is character (and not a factor), you can skip this step.</p>
</div>
<div class="footer">
This work is licensed under the <a href="http://creativecommons.org/licenses/by-nc/3.0/">CC BY-NC 3.0 Creative Commons License</a>.
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>