forked from jennybc/purrr-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex26_ny-food-market-json.html
More file actions
825 lines (753 loc) · 59.5 KB
/
Copy pathex26_ny-food-market-json.html
File metadata and controls
825 lines (753 loc) · 59.5 KB
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
<!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>Food Markets in New York</title>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/flatly.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-1.1/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-1.1/highlight.js"></script>
<script src="site_libs/htmlwidgets-0.8/htmlwidgets.js"></script>
<link href="site_libs/jsoneditor-5.5.5/jsoneditor.min.css" rel="stylesheet" />
<script src="site_libs/jsoneditor-5.5.5/jsoneditor.min.js"></script>
<script src="site_libs/jsonedit-binding-1.4.0/jsonedit.js"></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 && 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>
</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;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 60px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 65px;
margin-top: -65px;
}
.section h2 {
padding-top: 65px;
margin-top: -65px;
}
.section h3 {
padding-top: 65px;
margin-top: -65px;
}
.section h4 {
padding-top: 65px;
margin-top: -65px;
}
.section h5 {
padding-top: 65px;
margin-top: -65px;
}
.section h6 {
padding-top: 65px;
margin-top: -65px;
}
</style>
<script>
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')
.removeClass('toc-ignore')
.children('h1,h2,h3,h4,h5').addClass('toc-ignore');
// establish options
var options = {
selectors: "h1,h2,h3",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = true;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
padding-left: 25px;
text-indent: 0;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">purrr tutorial</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Lessons and examples</a>
</li>
<li>
<a href="more-resources.html">More resources</a>
</li>
<li>
<a href="slides.html">Slides</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="about.html">About</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Food Markets in New York</h1>
</div>
<p>Mara Averick <a href="https://twitter.com/dataandme/status/804385103178825729">recently tweeted</a> about a blog post from February 2015 by Zev Ross, demonstrating the conversion of JSON data into a data frame (<a href="http://zevross.com/blog/2015/02/12/using-r-to-download-and-parse-json-an-example-using-data-from-an-open-data-portal/">Using R to download and parse JSON: an example using data from an open data portal</a>). I thought it would be interesting to revisit this data wrangling task with purrr, which has only been on CRAN since fall 2015.</p>
<p>Zev is dealing with data on food markets in New York State that, sadly but realistically, cannot be well-represented in simple rectangular form, such as CSV. Therefore the data is available as JSON and it’s our job to turn it into a useful data frame. This is a very, very common task and a typical use case for purrr.</p>
<p><em>I downloaded and unpacked the zip archive provided by Zev: <a href="http://zevross.com/blog/wp-content/uploads/2015/02/foodMarkets.zip%5D">foodMarkets.zip</a>. These files are available in this tutorial’s repo in an unpacked state: <a href="https://github.com/jennybc/purrr-tutorial/tree/gh-pages/foodMarkets">foodMarkets</a>.</em></p>
<div id="load-packages-and-the-data" class="section level2">
<h2>Load packages and the data</h2>
<p>Packages used below:</p>
<ul>
<li>jsonlite for parsing JSON</li>
<li>purrr for obvious reasons</li>
<li>listviewer for doing recon on awkard lists</li>
<li>tibble and dplyr for forming and manipulating data frames, especially the “tibble” variant (class <code>tbl_df</code>), which is friendly to list-columns.</li>
</ul>
<pre class="r"><code>library(jsonlite)
#>
#> Attaching package: 'jsonlite'
#> The following object is masked from 'package:purrr':
#>
#> flatten
library(purrr)
library(listviewer)
library(tibble)
library(dplyr)
food_mkts_raw <- fromJSON("foodMarkets/retail_food_markets.json",
simplifyVector = FALSE)</code></pre>
</div>
<div id="voyage-of-discovery-data" class="section level2">
<h2>Voyage of discovery: <code>data</code></h2>
<p>When you first import JSON, it is common to have no clue what’s in there. You must explore.</p>
<pre class="r"><code>str(food_mkts_raw, max.level = 1)
#> List of 2
#> $ meta:List of 1
#> $ data:List of 28355
#> .. [list output truncated]</code></pre>
<p>Ooh, a <code>data</code> component sounds promising!</p>
<pre class="r"><code>str(food_mkts_raw$data, max.level = 1, list.len = 5)
#> List of 28355
#> $ :List of 23
#> .. [list output truncated]
#> $ :List of 23
#> .. [list output truncated]
#> $ :List of 23
#> .. [list output truncated]
#> $ :List of 23
#> .. [list output truncated]
#> $ :List of 23
#> .. [list output truncated]
#> [list output truncated]</code></pre>
<p>Working hypothesis: we have data of similar form for each of 28355 food markets. A slightly mysterious, but homogeneous list.</p>
<p>Pull out just the <code>data</code> component and store as <code>food_mkts</code>.</p>
<pre class="r"><code>food_mkts <- food_mkts_raw[["data"]]</code></pre>
</div>
<div id="voyage-of-discovery-meta-and-columns" class="section level2">
<h2>Voyage of discovery: <code>meta</code> and <code>columns</code></h2>
<p>Before we move on, what’s in the <code>meta</code> component of the raw JSON? It turns out we should focus on its sole component, which is named <code>view</code>.</p>
<pre class="r"><code>jsonedit(food_mkts_raw[[c("meta", "view")]])</code></pre>
<div id="htmlwidget-49cda215267c7db41420" style="width:672px;height:480px;" class="jsonedit html-widget"></div>
<script type="application/json" data-for="htmlwidget-49cda215267c7db41420">{"x":{"data":{"id":"9a8c-vfzj","name":"Retail Food Stores","attribution":"New York State Department of Agriculture and Markets","attributionLink":"http://www.agriculture.ny.gov/FS/FSHome.html","averageRating":0,"category":"Economic Development","createdAt":1361890199,"description":"A listing of all retail food stores which are licensed by the Department of Agriculture and Markets.","displayType":"table","downloadCount":1519,"indexUpdatedAt":1414627105,"newBackend":false,"numberOfComments":0,"oid":9007657,"publicationAppendEnabled":false,"publicationDate":1412263696,"publicationGroup":700965,"publicationStage":"published","rowsUpdatedAt":1412262837,"rowsUpdatedBy":"xzik-pf59","tableId":1750091,"totalTimesRated":0,"viewCount":24373,"viewLastModified":1412263696,"viewType":"tabular","columns":[{"id":-1,"name":"sid","dataTypeName":"meta_data","fieldName":":sid","position":0,"renderTypeName":"meta_data","format":{}},{"id":-1,"name":"id","dataTypeName":"meta_data","fieldName":":id","position":0,"renderTypeName":"meta_data","format":{}},{"id":-1,"name":"position","dataTypeName":"meta_data","fieldName":":position","position":0,"renderTypeName":"meta_data","format":{}},{"id":-1,"name":"created_at","dataTypeName":"meta_data","fieldName":":created_at","position":0,"renderTypeName":"meta_data","format":{}},{"id":-1,"name":"created_meta","dataTypeName":"meta_data","fieldName":":created_meta","position":0,"renderTypeName":"meta_data","format":{}},{"id":-1,"name":"updated_at","dataTypeName":"meta_data","fieldName":":updated_at","position":0,"renderTypeName":"meta_data","format":{}},{"id":-1,"name":"updated_meta","dataTypeName":"meta_data","fieldName":":updated_meta","position":0,"renderTypeName":"meta_data","format":{}},{"id":-1,"name":"meta","dataTypeName":"meta_data","fieldName":":meta","position":0,"renderTypeName":"meta_data","format":{}},{"id":169457637,"name":"County","dataTypeName":"text","description":"County this location is in","fieldName":"county","position":1,"renderTypeName":"text","tableColumnId":8179659,"width":137,"cachedContents":{"non_null":28355,"smallest":"Albany","null":0,"largest":"Yates","top":[{"count":20,"item":"Albany"},{"count":19,"item":"Broome"},{"count":18,"item":"Chautauqua"},{"count":17,"item":"Chemung"},{"count":16,"item":"Clinton"},{"count":15,"item":"Columbia"},{"count":14,"item":"Dutchess"},{"count":13,"item":"Erie"},{"count":12,"item":"Jefferson"},{"count":11,"item":"Monroe"},{"count":10,"item":"Nassau"},{"count":9,"item":"Niagara"},{"count":8,"item":"Oneida"},{"count":7,"item":"Onondaga"},{"count":6,"item":"Ontario"},{"count":5,"item":"Orange"},{"count":4,"item":"Oswego"},{"count":3,"item":"Rensselaer"},{"count":2,"item":"Rockland"},{"count":1,"item":"St. Lawrence"}]},"format":{"align":"left"}},{"id":169457638,"name":"License Number","dataTypeName":"text","description":"License number for this location","fieldName":"license_number","position":2,"renderTypeName":"text","tableColumnId":8179648,"width":183,"cachedContents":{"non_null":28355,"smallest":"100001","null":0,"largest":"95419","top":[{"count":20,"item":"641351"},{"count":19,"item":"641240"},{"count":18,"item":"641202"},{"count":17,"item":"641298"},{"count":16,"item":"641203"},{"count":15,"item":"641595"},{"count":14,"item":"641000"},{"count":13,"item":"641001"},{"count":12,"item":"641002"},{"count":11,"item":"641482"},{"count":10,"item":"641198"},{"count":9,"item":"641448"},{"count":8,"item":"641192"},{"count":7,"item":"641081"},{"count":6,"item":"641256"},{"count":5,"item":"641079"},{"count":4,"item":"641348"},{"count":3,"item":"641562"},{"count":2,"item":"641506"},{"count":1,"item":"641193"}]},"format":{"precisionStyle":"standard","noCommas":"true","align":"center"}},{"id":169457639,"name":"Operation Type","dataTypeName":"text","description":"Indicates the type of operation this \nlicensed entity conducts","fieldName":"operation_type","position":3,"renderTypeName":"text","tableColumnId":8179649,"width":176,"cachedContents":{"non_null":28355,"smallest":"Store","null":0,"largest":"Store","top":[{"count":20,"item":"Store"}]},"format":{"align":"center"}},{"id":169457640,"name":"Estab Type","dataTypeName":"text","fieldName":"estab_type","position":4,"renderTypeName":"text","tableColumnId":21635505,"width":162,"cachedContents":{"non_null":28355,"smallest":"A ","null":0,"largest":"JWBCA ","top":[{"count":20,"item":"JAC "},{"count":19,"item":"A "},{"count":18,"item":"JABH "},{"count":17,"item":"JAS "},{"count":16,"item":"JABC "},{"count":15,"item":"JACD "},{"count":14,"item":"JABHK "},{"count":13,"item":"JAB "},{"count":12,"item":"JACDK "},{"count":11,"item":"JACK "},{"count":10,"item":"JACH "},{"count":9,"item":"JABCHK"},{"count":8,"item":"JADK "},{"count":7,"item":"JAD "},{"count":6,"item":"JAW "},{"count":5,"item":"JAM "},{"count":4,"item":"JACDH "},{"count":3,"item":"JABCH "},{"count":2,"item":"JACHK "},{"count":1,"item":"JACO "}]},"format":{}},{"id":169457641,"name":"Entity Name","dataTypeName":"text","description":"Name of this licensed entity","fieldName":"entity_name","position":5,"renderTypeName":"text","tableColumnId":8179650,"width":232,"cachedContents":{"non_null":28355,"smallest":"$1 DEPOT INC ","null":0,"largest":"ZZ PETROLEUM INC ","top":[{"count":20,"item":"CVS ALBANY LLC "},{"count":19,"item":"WALGREEN EASTERN CO INC "},{"count":18,"item":"PORT RICHMOND DISCOUNT INC "},{"count":17,"item":"WATERFRONT GAS&CONVENIENCE LLC "},{"count":16,"item":"TAMAYO ALEJANDRO "},{"count":15,"item":"KANG SUNG HWAN "},{"count":14,"item":"YH NEW DORP INC "},{"count":13,"item":"EL JARDIN DELI & GROCERY INC "},{"count":12,"item":"ANTONIOS GOURMET LLC "},{"count":11,"item":"CONVENIENCE DISCOUNT INC "},{"count":10,"item":"FAMILY DOLLAR STORES OF NY INC "},{"count":9,"item":"HYLAN CONVENIENCE INC "},{"count":8,"item":"DOLLAR TREE STORES INC "},{"count":7,"item":"MSZ CORP "},{"count":6,"item":"ABOUNAJI DELI&GROCERY INC "}]},"format":{"align":"left"}},{"id":169457642,"name":"DBA Name","dataTypeName":"text","description":"Name this licensed entity is doing \nbusiness as","fieldName":"dba_name","position":6,"renderTypeName":"text","tableColumnId":8179651,"width":196,"cachedContents":{"non_null":28355,"smallest":" ","null":0,"largest":"ZW DELI&GROCERY ","top":[{"count":20,"item":"STUYVESANT PL DELI & GR"},{"count":19,"item":"RICHMOND DELI "},{"count":18,"item":"NET COST MARKETS "},{"count":17,"item":"DIANES DELI "},{"count":16,"item":"EHR GROCERY "},{"count":15,"item":"KING DELI OF THE ISLAND"},{"count":14,"item":"AFRICAN CARIB MKT "},{"count":13,"item":"FAMILY DELI "},{"count":12,"item":"SOUTH SHORE DELI "},{"count":11,"item":"VICTORY BLVD QUICK STOP"},{"count":10,"item":"TOP TOMATO #5 "},{"count":9,"item":"PORT RICHMOND DISCOUNT "},{"count":8,"item":"WATERFRONT GAS&CNVNC "},{"count":7,"item":"ACAPULCO BAKERY "},{"count":6,"item":"NEW HAPPY FARM "},{"count":5,"item":"YH NEW DORP "},{"count":4,"item":"EL JARDIN DELI & GRCRY "},{"count":3,"item":"ANTONIOS GOURMET "},{"count":2,"item":"CONVENIENCE DISCOUNT "},{"count":1,"item":"FAMILY DOLLAR #7795 "}]},"format":{"align":"left"}},{"id":169457643,"name":"Street Number","dataTypeName":"text","description":"Number of the location on a street","fieldName":"street_number","position":7,"renderTypeName":"text","tableColumnId":8179652,"width":174,"cachedContents":{"non_null":28023,"smallest":"1","null":332,"largest":"Oct-40","top":[{"count":20,"item":"151"},{"count":19,"item":"99"},{"count":18,"item":"1062"},{"count":17,"item":"1138"},{"count":16,"item":"7344"},{"count":15,"item":"149"},{"count":14,"item":"1071"},{"count":13,"item":"203"},{"count":12,"item":"1125"},{"count":11,"item":"166"},{"count":10,"item":"2500A"},{"count":9,"item":"268"},{"count":8,"item":"274"},{"count":7,"item":"7319"},{"count":6,"item":"327"},{"count":5,"item":"2264"},{"count":4,"item":"1150"},{"count":3,"item":"3231"},{"count":2,"item":"4300"},{"count":1,"item":"87"}]},"format":{"align":"center"}},{"id":169457644,"name":"Street Name","dataTypeName":"text","description":"1\nst address line of the physical address \nfor this location","fieldName":"street_name","position":8,"renderTypeName":"text","tableColumnId":8179653,"width":232,"cachedContents":{"non_null":28355,"smallest":" ","null":0,"largest":"ZEREGA AVE ","top":[{"count":20,"item":"BROADWAY "},{"count":19,"item":"JAMAICA AVE "},{"count":18,"item":"HYLAN BLVD "},{"count":17,"item":"PORT RICHMOND AVE "},{"count":16,"item":"VICTORY BLVD "},{"count":15,"item":"RICHMOND AVE "},{"count":14,"item":"AMBOY RD "},{"count":13,"item":"FOREST AVE "},{"count":12,"item":"RICHMOND TERR "},{"count":11,"item":"SOUTH AVE "},{"count":10,"item":"CLOVE RD "},{"count":9,"item":"FOREST AVE "},{"count":8,"item":"BROOK ST "},{"count":7,"item":"VICTORY BLVD "},{"count":6,"item":"NEW DORP LN "},{"count":5,"item":"VICTORY BLVD "},{"count":4,"item":"RHINE AVE "},{"count":3,"item":"MANOR RD "},{"count":2,"item":"FOREST AVE "},{"count":1,"item":"N RAILROAD AVE "}]},"format":{"align":"left"}},{"id":169457645,"name":"Address Line 2","dataTypeName":"text","description":"2\nnd address line of the physical address \nfor this location","fieldName":"address_line_2","position":9,"renderTypeName":"text","tableColumnId":8179654,"width":188,"cachedContents":{"non_null":28355,"smallest":" ","null":0,"largest":" ","top":[{"count":20,"item":" "}]},"format":{"align":"left"}},{"id":169457646,"name":"Address Line 3","dataTypeName":"text","description":"3\nrd address line of the physical address \nfor this location","fieldName":"address_line_3","position":10,"renderTypeName":"text","tableColumnId":8179655,"width":187,"cachedContents":{"non_null":28355,"smallest":" ","null":0,"largest":" ","top":[{"count":20,"item":" "}]},"format":{"align":"left"}},{"id":169457647,"name":"City","dataTypeName":"text","description":"City name of the physical address for \nthis location","fieldName":"city","position":11,"renderTypeName":"text","tableColumnId":8179656,"width":148,"cachedContents":{"non_null":28355,"smallest":"4EW YORK ","null":0,"largest":"YULAN ","top":[{"count":20,"item":"BUFFALO "},{"count":19,"item":"ROCHESTER "},{"count":18,"item":"SYRACUSE "},{"count":17,"item":"YONKERS "},{"count":16,"item":"MOUNT VERNON "},{"count":15,"item":"BRONX "},{"count":14,"item":"NEW YORK "},{"count":13,"item":"BROOKLYN "},{"count":12,"item":"ASTORIA "},{"count":11,"item":"JACKSON HEIGHTS "},{"count":10,"item":"JAMAICA "},{"count":9,"item":"ELMHURST "},{"count":8,"item":"LONG ISLAND CITY "},{"count":7,"item":"RIDGEWOOD "},{"count":6,"item":"CORONA "},{"count":5,"item":"FLUSHING "},{"count":4,"item":"OZONE PARK "},{"count":3,"item":"WOODSIDE "},{"count":2,"item":"RICHMOND HILL "},{"count":1,"item":"FOREST HILLS "}]},"format":{"align":"left"}},{"id":169457648,"name":"State","dataTypeName":"text","description":"2 character state code for the physical \naddress for this location","fieldName":"state","position":12,"renderTypeName":"text","tableColumnId":8179657,"width":123,"cachedContents":{"non_null":28355,"smallest":"NY","null":0,"largest":"NY","top":[{"count":20,"item":"NY"}]},"format":{"align":"left"}},{"id":169457649,"name":"Zip Code","dataTypeName":"number","description":"Zip code for the physical address for \nthis location","fieldName":"zip_code","position":13,"renderTypeName":"number","tableColumnId":8179658,"width":152,"cachedContents":{"non_null":28355,"smallest":"6390","sum":"334997029","null":0,"average":"11814.39001939693","largest":"14905","top":[{"count":20,"item":"10029"},{"count":19,"item":"10002"},{"count":18,"item":"11101"},{"count":17,"item":"11368"},{"count":16,"item":"11385"},{"count":15,"item":"11373"},{"count":14,"item":"11372"},{"count":13,"item":"11377"},{"count":12,"item":"11432"},{"count":11,"item":"11435"},{"count":10,"item":"11419"},{"count":9,"item":"11105"},{"count":8,"item":"11375"},{"count":7,"item":"11103"},{"count":6,"item":"11374"},{"count":5,"item":"11106"},{"count":4,"item":"11354"},{"count":3,"item":"11378"},{"count":2,"item":"11421"},{"count":1,"item":"11434"}]},"format":{"precisionStyle":"standard","align":"left","noCommas":"true"}},{"id":169457650,"name":"Square Footage","dataTypeName":"number","fieldName":"square_footage","position":14,"renderTypeName":"number","tableColumnId":21635506,"width":184,"cachedContents":{"non_null":28355,"smallest":"0","sum":"151863720","null":0,"average":"5355.800387938635","largest":"800000","top":[{"count":20,"item":"0"},{"count":19,"item":"2000"},{"count":18,"item":"1500"},{"count":17,"item":"1000"},{"count":16,"item":"1200"},{"count":15,"item":"800"},{"count":14,"item":"2500"},{"count":13,"item":"3000"},{"count":12,"item":"1800"},{"count":11,"item":"5000"},{"count":10,"item":"10000"},{"count":9,"item":"4000"},{"count":8,"item":"500"},{"count":7,"item":"600"},{"count":6,"item":"1600"},{"count":5,"item":"700"},{"count":4,"item":"900"},{"count":3,"item":"1100"},{"count":2,"item":"8000"},{"count":1,"item":"400"}]},"format":{}},{"id":169457651,"name":"Location","dataTypeName":"location","fieldName":"location","position":15,"renderTypeName":"location","tableColumnId":8179660,"width":196,"cachedContents":{"non_null":28355,"smallest":{"longitude":"-72.30174869299964","latitude":"40.93989944500049","human_address":"{\"address\":\"\",\"city\":\"BRIDGEHAMPTON\",\"state\":\"NY\",\"zip\":\"11932\"}"},"null":0,"largest":{"longitude":"-72.83257801499963","latitude":"40.95184821000049","human_address":"{\"address\":\"WILDWOOD STATE PARK\",\"city\":\"WADING RIVER\",\"state\":\"NY\",\"zip\":\"11792\"}"},"top":[{"count":20,"item":{"longitude":"-74.07728105399963","latitude":"40.643506190000494","human_address":"{\"address\":\"105 STUYVESANT PLACE\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10301\"}"}},{"count":19,"item":{"longitude":"-74.14904386899963","latitude":"40.624107507000474","human_address":"{\"address\":\"950 RICHMOND AVE\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10314\"}"}},{"count":18,"item":{"longitude":"-74.13193853099966","latitude":"40.56435765700047","human_address":"{\"address\":\"3155 AMBOY RD\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10306\"}"}},{"count":17,"item":{"longitude":"-74.07591446099963","latitude":"40.636006214000474","human_address":"{\"address\":\"248 BAY ST\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10301\"}"}},{"count":16,"item":{"longitude":"-74.13266200799967","latitude":"40.63720455200047","human_address":"{\"address\":\"151 VREELAND ST\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10302\"}"}},{"count":15,"item":{"longitude":"-74.07674308299966","latitude":"40.62711631700046","human_address":"{\"address\":\"99 WATER ST\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10304\"}"}},{"count":14,"item":{"longitude":"-74.11812189399967","latitude":"40.63446295500046","human_address":"{\"address\":\"1062 CASTLETON AVE\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10310\"}"}},{"count":13,"item":{"longitude":"-74.12052463599963","latitude":"40.63424646800047","human_address":"{\"address\":\"1138 CASTLETON AVE\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10310\"}"}},{"count":12,"item":{"longitude":"-74.24185748799965","latitude":"40.51084900800049","human_address":"{\"address\":\"7344 AMBOY RD\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10307\"}"}},{"count":11,"item":{"longitude":"-74.08099557499963","latitude":"40.637129797000455","human_address":"{\"address\":\"149 VICTORY BLVD\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10301\"}"}},{"count":10,"item":{"longitude":"-74.06803202799966","latitude":"40.61673285800049","human_address":"{\"address\":\"1071 BAY ST\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10305\"}"}},{"count":9,"item":{"longitude":"-74.13453631799968","latitude":"40.63632217200046","human_address":"{\"address\":\"203 PORT RICHMOND AVE\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10302\"}"}},{"count":8,"item":{"longitude":"-74.10819548299963","latitude":"40.645226022000486","human_address":"{\"address\":\"1125 RICHMOND TERRACE\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10310\"}"}},{"count":7,"item":{"longitude":"-74.14608802899966","latitude":"40.6338864170005","human_address":"{\"address\":\"166 MORNINGSTAR RD\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10303\"}"}},{"count":6,"item":{"longitude":"-74.14654835399966","latitude":"40.61020816400048","human_address":"{\"address\":\"2500A VICTORY BLVD\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10314\"}"}},{"count":5,"item":{"longitude":"-74.11326795699966","latitude":"40.57232190700046","human_address":"{\"address\":\"268 NEW DORP LN\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10306\"}"}},{"count":4,"item":{"longitude":"-74.06828251299964","latitude":"40.59265918000045","human_address":"{\"address\":\"274 SAND LN\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10305\"}"}},{"count":3,"item":{"longitude":"-74.24129571499964","latitude":"40.511181182000485","human_address":"{\"address\":\"7319 AMBOY RD\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10307\"}"}},{"count":2,"item":{"longitude":"-74.08571296999963","latitude":"40.63406429100047","human_address":"{\"address\":\"327 VICTORY BLVD\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10301\"}"}},{"count":1,"item":{"longitude":"-74.16506334299964","latitude":"40.62707022400048","human_address":"{\"address\":\"2264 FOREST AVE\",\"city\":\"STATEN ISLAND\",\"state\":\"NY\",\"zip\":\"10303\"}"}}]},"format":{},"subColumnTypes":["human_address","latitude","longitude","machine_address","needs_recoding"]}],"grants":[{"inherited":false,"type":"viewer","flags":["public"]}],"metadata":{"custom_fields":{"Dataset Summary":{"Granularity":"County","Coverage":"Statewide","Data Frequency":"Biennially","Posting Frequency":"Annually","Units":"Establishment","Dataset Owner":"Division of Food Safety & Inspection","Organization":"Division of Food Safety & Inspection","Time Period":"Snapshot"},"Disclaimers":{"Limitations":"This dataset is from a snap-shot in time and may not always reflect the day-to-day operations of an establishment."},"Dataset Information":{"Agency":"Agriculture and Markets, Department of"},"Local Data":{"County Filter":"Yes","County_Column":"county","Municipality_Column":"city","Municipality Filter":"Yes"}},"renderTypeConfig":{"visible":{"table":true}},"availableDisplayTypes":["table","fatrow","page"],"rdfSubject":"0","attachments":[{"assetId":"","blobId":"5CFC751A-D71C-4B73-AB73-4EB25BFCDB89","name":"NYSDAM_RetailFoodStores_Overview.pdf","filename":"NYSDAM_RetailFoodStores_Overview.pdf"},{"assetId":"nQmIjwR3EmW9F6fHgph6wYyFEevnLQ7WrygWk49NyFY","name":"NYSDAM_RetailFoodStores_DataFileLayout.pdf","filename":"NYSDAM_RetailFoodStores_DataFileLayout.pdf"},{"assetId":"UBDP3oW2f-K767I4f51EJaIUO8eNGPrAQQj8tSvBhbo","name":"EstabType_CodeReference.pdf","filename":"EstabType_CodeReference.pdf"}]},"owner":{"id":"xzik-pf59","displayName":"NY Open Data","profileImageUrlLarge":"/images/profile/5700/9521/image_large.jpg","profileImageUrlMedium":"/images/profile/5700/9521/image_thumb.jpg","profileImageUrlSmall":"/images/profile/5700/9521/image_tiny.jpg","roleName":"publisher","screenName":"NY Open Data","rights":["create_datasets","edit_others_datasets","edit_nominations","approve_nominations","moderate_comments","manage_stories","feature_items","change_configurations","view_domain","view_others_datasets","create_pages","edit_pages","view_goals","view_dashboards","edit_goals","edit_dashboards"]},"query":{},"rights":["read"],"tableAuthor":{"id":"xzik-pf59","displayName":"NY Open Data","profileImageUrlLarge":"/images/profile/5700/9521/image_large.jpg","profileImageUrlMedium":"/images/profile/5700/9521/image_thumb.jpg","profileImageUrlSmall":"/images/profile/5700/9521/image_tiny.jpg","roleName":"publisher","screenName":"NY Open Data","rights":["create_datasets","edit_others_datasets","edit_nominations","approve_nominations","moderate_comments","manage_stories","feature_items","change_configurations","view_domain","view_others_datasets","create_pages","edit_pages","view_goals","view_dashboards","edit_goals","edit_dashboards"]},"tags":["retail food store","food safety","license"],"flags":["default"]},"options":{"mode":"tree","modes":["code","form","text","tree","view"]}},"evals":[],"jsHooks":[]}</script>
<p>The <code>columns</code> component is especially valuable, because it tells us what data we have for each food market over in the <code>data</code> component. This is an example of a common but, in my opinion, dangerous practice of storing information with no explanatory names and providing a separate lexicon. This is kind of like a CSV with variables named <code>X1</code> through <code>Xn</code> or no names at all.</p>
<p>We need to pull out the <code>name</code> elements of <code>columns</code>. We kick off with <code>[[</code> vector indexing into a nested list, to drill down to the <code>columns</code> sub-component. Then <code>map_chr(..., "name")</code> to grab the <code>name</code>s as character vector.</p>
<pre class="r"><code>(cnames <- food_mkts_raw[[c("meta", "view", "columns")]] %>%
map_chr("name"))
#> [1] "sid" "id" "position" "created_at"
#> [5] "created_meta" "updated_at" "updated_meta" "meta"
#> [9] "County" "License Number" "Operation Type" "Estab Type"
#> [13] "Entity Name" "DBA Name" "Street Number" "Street Name"
#> [17] "Address Line 2" "Address Line 3" "City" "State"
#> [21] "Zip Code" "Square Footage" "Location"</code></pre>
</div>
<div id="apply-names" class="section level2">
<h2>Apply names</h2>
<p>Downstream work will be easier if the food market elements bear the names in <code>cnames</code>. I believe this is how the JSON should have been to begin with. This makes exploration and troubleshooting easier and, more importantly, it helps in our goal to create a data frame.</p>
<pre class="r"><code>food_mkts <- food_mkts %>%
map(set_names, cnames)</code></pre>
</div>
<div id="one-variable" class="section level2">
<h2>One variable</h2>
<p>As a warm-up activity, pull out and simplify the data for one column, across all food markets. From Zev’s post, I decided to look at <code>DBA Name</code> (“doing business as”).</p>
<pre class="r"><code>food_mkts %>%
map_chr("DBA Name") %>%
head()
#> [1] "PLAZA 23 TRUCK STOP " "PRICE CHOPPER #245 "
#> [3] "PEACOCK " "FINYOUR FISHMONGER "
#> [5] "R&A GROCERY STORE " "ANTHONYS CHOC DIP FRUIT"</code></pre>
<p>I think we’ll want to trim whitespace at some point!</p>
</div>
<div id="data-frame-of-almost-everything" class="section level2">
<h2>Data frame of (almost) everything</h2>
<p>Again, freeriding on Zev’s post, I know that 22 of the 23 variables can be extracted in a fairly simple way. Everything but <code>Location</code>, which holds some unparsed JSON we must tackle separately.</p>
<p>Create a vector of our targetted variable names:</p>
<pre class="r"><code>(to_process <- cnames[cnames != "Location"])
#> [1] "sid" "id" "position" "created_at"
#> [5] "created_meta" "updated_at" "updated_meta" "meta"
#> [9] "County" "License Number" "Operation Type" "Estab Type"
#> [13] "Entity Name" "DBA Name" "Street Number" "Street Name"
#> [17] "Address Line 2" "Address Line 3" "City" "State"
#> [21] "Zip Code" "Square Footage"</code></pre>
<p><strong>Goal: create a data frame with these variables and one row per food market.</strong></p>
<div id="rows-first" class="section level3">
<h3>“Rows first”</h3>
<p>Voice from the future: not all of these 22 variables are populated for every food market. There are explicit <code>NULL</code>s. Zev handled this with a two-layered approach: catch the <code>NULL</code>s and replace with <code>NA</code>s, prior to combining with data from other markets via <code>sapply()</code> and <code>data.frame()</code>.</p>
<p>purrr’s handling of void, explicit <code>NULL</code>, and implicit <code>NULL</code> is quite good, but doesn’t address this case either. Therefore I too must fanny around with <code>NULL</code>s before I can make my beautiful data frame.</p>
<p>Ideally, I would use <code>map_df()</code> like this for food markets instead of just the first 3:</p>
<pre class="r"><code>food_mkts[1:3] %>%
map_df(`[`, to_process)
#> # A tibble: 3 × 22
#> sid id position created_at
#> <int> <chr> <int> <int>
#> 1 1 D943D633-8DB5-4740-B5F4-06AAB6FC52E2 1 1412261567
#> 2 2 7A069C98-90B2-4B11-A4A7-3C4761D14DDD 2 1412261567
#> 3 3 68DBE61E-ACF4-4803-BD90-87380FDAA4F9 3 1412261567
#> # ... with 18 more variables: created_meta <chr>, updated_at <int>,
#> # updated_meta <chr>, meta <chr>, County <chr>, `License Number` <chr>,
#> # `Operation Type` <chr>, `Estab Type` <chr>, `Entity Name` <chr>, `DBA
#> # Name` <chr>, `Street Number` <chr>, `Street Name` <chr>, `Address Line
#> # 2` <chr>, `Address Line 3` <chr>, City <chr>, State <chr>, `Zip
#> # Code` <chr>, `Square Footage` <chr></code></pre>
<p>But I have learned the hard way that the <code>NULL</code>s are a dealkiller.</p>
<p>How does <code>map_df()</code> actually work? First, it calls <code>map()</code> and, in my application, gets the sub-list of non-<code>Location</code> variables for each food market. Then a list of these lists is shipped off to <code>dplyr::bind_rows()</code> for row-binding and type conversion. But the presence of <code>NULL</code>s breaks this workflow when there are markets, like the one below, that lack, say, a street number. Basically most of R’s data-frame-making facilities balk at <code>NULL</code>s. Here is some exploration of that.</p>
<pre class="r"><code>food_mkts[[67]][14:16]
#> $`DBA Name`
#> [1] "PORTOBELLA PETES "
#>
#> $`Street Number`
#> NULL
#>
#> $`Street Name`
#> [1] "BLDG 12 STATE CAMPUS DOL "
data.frame(food_mkts[[67]][14:16])
#> Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 1, 0
food_mkts[66:68] %>%
map_df(`[`, to_process)
#> Error in eval(expr, envir, enclos): incompatible sizes (1 != 0)</code></pre>
<p>I want to rescue this workflow, because the automatic type conversion from <code>dplyr::bind_rows()</code> is very appealing.</p>
<p>Therefore, like Zev, I use a custom function <code>safe_extract()</code>. It’s a slightly expanded version of <code>[</code> that replaces <code>NULL</code> with <code>NA</code>.</p>
<pre class="r"><code>safe_extract <- function(l, wut) {
res <- l[wut]
null_here <- map_lgl(res, is.null)
res[null_here] <- NA
res
}
safe_extract(food_mkts[[67]][14:16])
#> $`DBA Name`
#> [1] "PORTOBELLA PETES "
#>
#> $`Street Number`
#> [1] NA
#>
#> $`Street Name`
#> [1] "BLDG 12 STATE CAMPUS DOL "</code></pre>
<p>Now I can get a data frame easily.</p>
<pre class="r"><code>(mkts_df <- food_mkts %>%
map_df(safe_extract, to_process))
#> # A tibble: 28,355 × 22
#> sid id position created_at
#> <int> <chr> <int> <int>
#> 1 1 D943D633-8DB5-4740-B5F4-06AAB6FC52E2 1 1412261567
#> 2 2 7A069C98-90B2-4B11-A4A7-3C4761D14DDD 2 1412261567
#> 3 3 68DBE61E-ACF4-4803-BD90-87380FDAA4F9 3 1412261567
#> 4 4 9DA5A827-A0AD-4782-8CE2-5D6867B53293 4 1412261567
#> 5 5 5D624E4B-E4A8-4F3D-BF88-190663DF8FCF 5 1412261567
#> 6 6 86BC29A4-55DA-43C5-BDED-6EF2C92C3C8B 6 1412261567
#> 7 7 51EE0EB4-6D71-4C2E-AD44-E225A1A45987 7 1412261567
#> 8 8 22B148DF-F188-4245-8E69-1137F9A6064E 8 1412261567
#> 9 9 62526ABF-801E-46DE-97CD-05C2DDE6BB20 9 1412261567
#> 10 10 13153CBA-3E65-4D4D-9A4C-ACB24BCD33DF 10 1412261567
#> # ... with 28,345 more rows, and 18 more variables: created_meta <chr>,
#> # updated_at <int>, updated_meta <chr>, meta <chr>, County <chr>,
#> # `License Number` <chr>, `Operation Type` <chr>, `Estab Type` <chr>,
#> # `Entity Name` <chr>, `DBA Name` <chr>, `Street Number` <chr>, `Street
#> # Name` <chr>, `Address Line 2` <chr>, `Address Line 3` <chr>,
#> # City <chr>, State <chr>, `Zip Code` <chr>, `Square Footage` <chr></code></pre>
<p>Victory is ours. Well, partial victory. We still need to deal with <code>Location</code>.</p>
</div>
<div id="rows-first-recap" class="section level3">
<h3>“Rows first” Recap</h3>
<p>Self-contained code to go from raw JSON to data frame for 22 out of 23 variables, relying on automatic type conversion.</p>
<pre class="r"><code>food_mkts_raw <- fromJSON("foodMarkets/retail_food_markets.json",
simplifyVector = FALSE)
cnames <- food_mkts_raw[[c("meta", "view", "columns")]] %>%
map_chr("name")
food_mkts <- food_mkts_raw[["data"]] %>%
map(set_names, cnames)
to_process <- cnames[cnames != "Location"]
safe_extract <- function(l, wut) {
res <- l[wut]
null_here <- map_lgl(res, is.null)
res[null_here] <- NA
res
}
mkts_df <- food_mkts %>%
map_df(safe_extract, to_process)</code></pre>
</div>
<div id="columns-first" class="section level3">
<h3>“Columns first”</h3>
<p>The more proper workflow is to build the columns first, with purrr’s type-specific mapping functions, then put them into a data frame. This is safer because it forces you to articulate and enforce type expectations for each variable.</p>
<ul>
<li>Good news: there’s a built-in way to handle explicit <code>NULL</code>s.</li>
<li>Bad news: we need to specify type for each of the 22 variables.</li>
<li>¯\_(ツ)_/¯ news: we get to use more exotic features of purrr.</li>
</ul>
<p>Here’s a naïve approach for two variables:</p>
<pre class="r"><code>food_mkts %>% {
tibble(
dba_name = map_chr(., "DBA Name"),
city = map_chr(., "City")
)
}
#> # A tibble: 28,355 × 2
#> dba_name city
#> <chr> <chr>
#> 1 PLAZA 23 TRUCK STOP ALBANY
#> 2 PRICE CHOPPER #245 WATERVLIET
#> 3 PEACOCK ALBANY
#> 4 FINYOUR FISHMONGER GUILDERLAND
#> 5 R&A GROCERY STORE ALBANY
#> 6 ANTHONYS CHOC DIP FRUIT ALBANY
#> 7 DOLLAR TREE #4168 GLENMONT
#> 8 GREAT WALL EXPRESS ASIA SLINGERLANDS
#> 9 INANC I OZBAY ALBANY
#> 10 SAGAMIA SLINGERLANDS
#> # ... with 28,345 more rows</code></pre>
<p>Doing this for 22 variables is a drag, though it’s certainly possible, and even reasonable for the ingest of an important dataset.</p>
<p>However, because I can, I store the type of each variable and do extraction + type conversion programmatically. This lets us explore more of the functional programming side of purrr.</p>
<p>I exploit the variable types learned from the automatic type conversion in the “rows first” approach. Here’s a data frame with one row per variable, providing the expected class and the type-appropriate <code>map_*()</code> and <code>NA</code>. It will soon become clear why I use the specific variable names, <code>.f</code> and <code>.null</code>.</p>
<pre class="r"><code>(vdf <- mkts_df %>%
map_chr(class) %>%
enframe(name = ".f", value = "type") %>%
mutate(vname = .f %>% tolower() %>% gsub("\\s+", "_", .),
mapper = c(integer = "map_int", character = "map_chr")[type],
.null = list(integer = NA_integer_,
character = NA_character_)[type]))
#> # A tibble: 22 × 5
#> .f type vname mapper .null
#> <chr> <chr> <chr> <chr> <list>
#> 1 sid integer sid map_int <int [1]>
#> 2 id character id map_chr <chr [1]>
#> 3 position integer position map_int <int [1]>
#> 4 created_at integer created_at map_int <int [1]>
#> 5 created_meta character created_meta map_chr <chr [1]>
#> 6 updated_at integer updated_at map_int <int [1]>
#> 7 updated_meta character updated_meta map_chr <chr [1]>
#> 8 meta character meta map_chr <chr [1]>
#> 9 County character county map_chr <chr [1]>
#> 10 License Number character license_number map_chr <chr [1]>
#> # ... with 12 more rows</code></pre>
<p>Here’s how I could use <code>do.call()</code> to create one variable based on one row of this data frame.</p>
<pre class="r"><code>i <- 14 # DBA Name
vdf[i, ]
#> # A tibble: 1 × 5
#> .f type vname mapper .null
#> <chr> <chr> <chr> <chr> <list>
#> 1 DBA Name character dba_name map_chr <chr [1]>
do.call(vdf$mapper[i],
list(.x = food_mkts, .f = vdf$.f[i], .null = vdf$.null[[i]])) %>%
head()
#> [1] "PLAZA 23 TRUCK STOP " "PRICE CHOPPER #245 "
#> [3] "PEACOCK " "FINYOUR FISHMONGER "
#> [5] "R&A GROCERY STORE " "ANTHONYS CHOC DIP FRUIT"</code></pre>
<p><code>do.call()</code> is a base R function that constructs and executes a function call from a function (name or actual function) and a list of arguments. It’s exactly what we need. But we also want to do this for each of the 22 variables.</p>
<p>How to scale up? We use the <code>invoke()</code> family of functions in purrr. <code>invoke()</code> itself is a pipe-friendly wrapper around <code>do.call()</code>. <code>invoke_map()</code> and friends allow you to map over functions and arguments in parallel, analagous to <code>map2()</code>. The big difference with <code>invoke_map()</code> is that the two primary inputs are a vector of functions and a vector of argument values. We use <code>invoke_map_df()</code> here, which is the variant that requests to get a data frame back.</p>
<pre class="r"><code>(mkts_df <- invoke_map_df(.f = set_names(vdf$mapper, vdf$vname),
.x = transpose(vdf[c(".f", ".null")]),
food_mkts))
#> # A tibble: 28,355 × 22
#> sid id position created_at
#> <int> <chr> <int> <int>
#> 1 1 D943D633-8DB5-4740-B5F4-06AAB6FC52E2 1 1412261567
#> 2 2 7A069C98-90B2-4B11-A4A7-3C4761D14DDD 2 1412261567
#> 3 3 68DBE61E-ACF4-4803-BD90-87380FDAA4F9 3 1412261567
#> 4 4 9DA5A827-A0AD-4782-8CE2-5D6867B53293 4 1412261567
#> 5 5 5D624E4B-E4A8-4F3D-BF88-190663DF8FCF 5 1412261567
#> 6 6 86BC29A4-55DA-43C5-BDED-6EF2C92C3C8B 6 1412261567
#> 7 7 51EE0EB4-6D71-4C2E-AD44-E225A1A45987 7 1412261567
#> 8 8 22B148DF-F188-4245-8E69-1137F9A6064E 8 1412261567
#> 9 9 62526ABF-801E-46DE-97CD-05C2DDE6BB20 9 1412261567
#> 10 10 13153CBA-3E65-4D4D-9A4C-ACB24BCD33DF 10 1412261567
#> # ... with 28,345 more rows, and 18 more variables: created_meta <chr>,
#> # updated_at <int>, updated_meta <chr>, meta <chr>, county <chr>,
#> # license_number <chr>, operation_type <chr>, estab_type <chr>,
#> # entity_name <chr>, dba_name <chr>, street_number <chr>,
#> # street_name <chr>, address_line_2 <chr>, address_line_3 <chr>,
#> # city <chr>, state <chr>, zip_code <chr>, square_footage <chr></code></pre>
<p>Partial victory is ours again! A data frame, one row per food market, with 22 variables. How did this work? Line-by-line:</p>
<ul>
<li><code>.f = set_names(vdf$mapper, vdf$vname)</code> specifies the list of functions to iterate over: the type-specific mappers we pre-selected above. I bother to apply names here because they propagate to the variable names of the data frame.</li>
<li><code>.x = transpose(vdf[c(".f", ".null")])</code> gives the parallel list of function arguments, namely the strings specifying named elements to extract and the value to insert in place of explicit <code>NULL</code>. Two things that might be confusing:
<ul>
<li>This instance of <code>.f</code> is at the variable level, i.e. inside our iteration. In the previous line, <code>.f</code> refers to the overall operation, i.e. setting up our iteration.</li>
<li><code>transpose()</code> is needed to repackage the <code>.f</code> and <code>.null</code> variables. Instead of a list of two same-length vectors, we want a single list holding lists of length two.</li>
</ul></li>
<li><code>food_mkts</code> is the <code>...</code> argument. It’s a common input across all units of iteration.</li>
</ul>
</div>
<div id="columns-first-recap" class="section level3">
<h3>“Columns first” Recap</h3>
<p>Self-contained code to go from raw JSON to data frame for 22 out of 23 variables, with explicit type specification.</p>
<pre class="r"><code>food_mkts_raw <- fromJSON("foodMarkets/retail_food_markets.json",
simplifyVector = FALSE)
cnames <- food_mkts_raw[[c("meta", "view", "columns")]] %>%
map_chr("name")
food_mkts <- food_mkts_raw[["data"]] %>%
map(set_names, cnames)
vdf <- tribble(
~ .f, ~ type,
"sid", "integer",
"id", "character",
"position", "integer",
"created_at", "integer",
"created_meta", "character",
"updated_at", "integer",
"updated_meta", "character",
"meta", "character",
"County", "character",
"License Number", "character",
"Operation Type", "character",
"Estab Type", "character",
"Entity Name", "character",
"DBA Name", "character",
"Street Number", "character",
"Street Name", "character",
"Address Line 2", "character",
"Address Line 3", "character",
"City", "character",
"State", "character",
"Zip Code", "character",
"Square Footage", "character")
vdf <- vdf %>%
mutate(vname = .f %>% tolower() %>% gsub("\\s+", "_", .),
mapper = c(integer = "map_int", character = "map_chr")[type],
.null = list(integer = NA_integer_,
character = NA_character_)[type])
mkts_df <- invoke_map_df(.f = set_names(vdf$mapper, vdf$vname),
.x = transpose(vdf[c(".f", ".null")]),
food_mkts)</code></pre>
</div>
</div>
<div id="rescue-location" class="section level2">
<h2>Rescue <code>Location</code></h2>
<p>We need to process the 23rd variable, <code>Location</code>. There are no big new principles here, so this will heavy on the code and light on explanation.</p>
<div id="prepare-location" class="section level3">
<h3>Prepare <code>Location</code></h3>
<p>Pull <code>Location</code> into its own list and inspect one element.</p>
<pre class="r"><code>loc_raw <- food_mkts %>%
map("Location")
loc_raw[[345]]
#> [[1]]
#> [1] "{\"address\":\"196 VLIET BLVD\",\"city\":\"COHOES\",\"state\":\"NY\",\"zip\":\"12047\"}"
#>
#> [[2]]
#> [1] "42.77787640800045"
#>
#> [[3]]
#> [1] "-73.71585755099966"
#>
#> [[4]]
#> NULL
#>
#> [[5]]
#> [1] FALSE</code></pre>
<p>Ah, more key-less JSON, giving rise to name-less lists. Before we do anything else, extract names from the <code>meta</code> component and apply them. Re-inspect an element to verify we’ve succeeded.</p>
<pre class="r"><code>i <- which(cnames == "Location")
location_meta <- food_mkts_raw[[c("meta", "view", "columns")]][[i]]
(lnames <- location_meta[["subColumnTypes"]] %>% flatten_chr())
#> [1] "human_address" "latitude" "longitude" "machine_address"
#> [5] "needs_recoding"
loc_raw <- loc_raw %>%
map(set_names, lnames)
loc_raw[[345]]
#> $human_address
#> [1] "{\"address\":\"196 VLIET BLVD\",\"city\":\"COHOES\",\"state\":\"NY\",\"zip\":\"12047\"}"
#>
#> $latitude
#> [1] "42.77787640800045"
#>
#> $longitude
#> [1] "-73.71585755099966"
#>
#> $machine_address
#> NULL
#>
#> $needs_recoding
#> [1] FALSE</code></pre>
</div>
<div id="parse-the-json-string-holding-human-address" class="section level3">
<h3>Parse the JSON string holding human address</h3>
<p>The <code>human_address</code> element of each location holds a JSON string:</p>
<ul>
<li>Parse it.</li>
<li>Rowbind elements into a data frame.</li>
<li>Prepend <code>ha_</code> to the variable names to avoid name conflicts downstream.</li>
</ul>
<pre class="r"><code>ha <- loc_raw %>%
map("human_address") %>%
map_df(fromJSON) %>%
set_names(paste0("ha_", names(.)))
head(ha)
#> # A tibble: 6 × 4
#> ha_address ha_city ha_state ha_zip
#> <chr> <chr> <chr> <chr>
#> 1 240 CHURCH ST #242 ALBANY NY 12202
#> 2 515 19TH ST WATERVLIET NY 12189
#> 3 795 BROADWAY ALBANY NY 12207
#> 4 2050 WESTERN AVE GUILDERLAND NY 12084
#> 5 265 CENTRAL AVE ALBANY NY 12206
#> 6 1693 CENTRAL AVE ALBANY NY 12205</code></pre>
</div>
<div id="convert-remaining-variables-into-a-data-frame" class="section level3">
<h3>Convert remaining variables into a data frame</h3>
<p>Convert everything else left in the location data to a data frame. Convert <code>latitude</code> and <code>longitude</code> into numeric variables and make sure they don’t look insane. <a href="http://www.mapsofworld.com/usa/states/new-york/lat-long.html">This New York latitude and longitude map</a> indicates that latitude should range between 40° and 50° and longitude between -80° and -72°.</p>
<pre class="r"><code>ee <- loc_raw %>%
map_df(safe_extract, lnames[lnames != "human_address"]) %>%
mutate_at(vars(latitude, longitude), as.numeric)
head(ee)
#> # A tibble: 6 × 4
#> latitude longitude machine_address needs_recoding
#> <dbl> <dbl> <lgl> <lgl>
#> 1 42.63541 -73.75541 NA FALSE
#> 2 42.73111 -73.70496 NA FALSE
#> 3 42.65794 -73.74780 NA FALSE
#> 4 42.69787 -73.88924 NA FALSE
#> 5 42.66340 -73.77088 NA FALSE
#> 6 42.72312 -73.83912 NA FALSE
ee %>%
select(latitude, longitude) %>%
map(summary)
#> $latitude
#> Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
#> 40.51 40.71 40.84 41.46 42.45 45.00 1
#>
#> $longitude
#> Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
#> -79.75 -74.18 -73.94 -74.58 -73.84 -71.92 1</code></pre>
</div>
</div>
<div id="put-everything-together" class="section level2">
<h2>Put everything together</h2>
<p>Column bind the main data frame <code>mkts_df</code> with the human address data in <code>ha</code> and everything else from <code>Location</code>.</p>
<pre class="r"><code>(mkts_df <- bind_cols(mkts_df, ha, ee))
#> # A tibble: 28,355 × 30
#> sid id position created_at
#> <int> <chr> <int> <int>
#> 1 1 D943D633-8DB5-4740-B5F4-06AAB6FC52E2 1 1412261567
#> 2 2 7A069C98-90B2-4B11-A4A7-3C4761D14DDD 2 1412261567
#> 3 3 68DBE61E-ACF4-4803-BD90-87380FDAA4F9 3 1412261567
#> 4 4 9DA5A827-A0AD-4782-8CE2-5D6867B53293 4 1412261567
#> 5 5 5D624E4B-E4A8-4F3D-BF88-190663DF8FCF 5 1412261567
#> 6 6 86BC29A4-55DA-43C5-BDED-6EF2C92C3C8B 6 1412261567
#> 7 7 51EE0EB4-6D71-4C2E-AD44-E225A1A45987 7 1412261567
#> 8 8 22B148DF-F188-4245-8E69-1137F9A6064E 8 1412261567
#> 9 9 62526ABF-801E-46DE-97CD-05C2DDE6BB20 9 1412261567
#> 10 10 13153CBA-3E65-4D4D-9A4C-ACB24BCD33DF 10 1412261567
#> # ... with 28,345 more rows, and 26 more variables: created_meta <chr>,
#> # updated_at <int>, updated_meta <chr>, meta <chr>, county <chr>,
#> # license_number <chr>, operation_type <chr>, estab_type <chr>,
#> # entity_name <chr>, dba_name <chr>, street_number <chr>,
#> # street_name <chr>, address_line_2 <chr>, address_line_3 <chr>,
#> # city <chr>, state <chr>, zip_code <chr>, square_footage <chr>,
#> # ha_address <chr>, ha_city <chr>, ha_state <chr>, ha_zip <chr>,
#> # latitude <dbl>, longitude <dbl>, machine_address <lgl>,
#> # needs_recoding <lgl></code></pre>
<p>Trim any leading/trailing whitespace from the character variables.</p>
<pre class="r"><code>mkts_df <- mkts_df %>%
mutate_if(is.character, trimws)</code></pre>
<p>Take a look at some of the most interpretable variables.</p>
<pre class="r"><code>mkts_df %>%
select(dba_name, city, latitude, longitude, square_footage)
#> # A tibble: 28,355 × 5
#> dba_name city latitude longitude square_footage
#> <chr> <chr> <dbl> <dbl> <chr>
#> 1 PLAZA 23 TRUCK STOP ALBANY 42.63541 -73.75541 3600
#> 2 PRICE CHOPPER #245 WATERVLIET 42.73111 -73.70496 0
#> 3 PEACOCK ALBANY 42.65794 -73.74780 2000
#> 4 FINYOUR FISHMONGER GUILDERLAND 42.69787 -73.88924 2100
#> 5 R&A GROCERY STORE ALBANY 42.66340 -73.77088 1500
#> 6 ANTHONYS CHOC DIP FRUIT ALBANY 42.72312 -73.83912 0
#> 7 DOLLAR TREE #4168 GLENMONT 42.60176 -73.79454 10000
#> 8 GREAT WALL EXPRESS ASIA SLINGERLANDS 42.64117 -73.86302 0
#> 9 INANC I OZBAY ALBANY 42.71746 -73.83267 0
#> 10 SAGAMIA SLINGERLANDS 42.64117 -73.86302 1000
#> # ... with 28,345 more rows</code></pre>
</div>
<p><a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/"><img alt="Creative Commons License" style="border-width:0" src="by-nc.png" height="400" width="65"/></a></p>
</div>
</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://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>