-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.html
1171 lines (1059 loc) · 78.7 KB
/
index.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
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<meta name="author" content="Dr. Naomi Zimmerman" />
<meta name="date" content="2023-10-02" />
<title>AAAR 2023 Data Wrangling Tutorial</title>
<script src="site_libs/header-attrs-2.25/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/cerulean.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>
<style>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;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<script src="site_libs/navigation-1.1/codefolding.js"></script>
<script src="site_libs/navigation-1.1/sourceembed.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</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">
#rmd-source-code {
display: none;
}
</style>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
details > summary > p:only-child {
display: inline;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// 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 the anchor link active (and if it's in a dropdown, also mark that active)
var dropdown = menuAnchor.closest('li.dropdown');
if (window.bootstrap) { // Bootstrap 4+
menuAnchor.addClass('active');
dropdown.find('> .dropdown-toggle').addClass('active');
} else { // Bootstrap 3
menuAnchor.parent().addClass('active');
dropdown.addClass('active');
}
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before, .tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "\e259";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "\e258";
font-family: 'Glyphicons Halflings';
border: none;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
.code-folding-btn { margin-bottom: 4px; }
</style>
</head>
<body>
<div class="container-fluid main-container">
<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-bs-toggle="collapse" data-target="#navbar" data-bs-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">2023 Data Wrangling Tutorial</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="index.html">Home</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<div class="btn-group pull-right float-right">
<button type="button" class="btn btn-default btn-xs btn-secondary btn-sm dropdown-toggle" data-toggle="dropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span>Code</span> <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-right" style="min-width: 50px;">
<li><a id="rmd-download-source" href="#">Download Rmd</a></li>
</ul>
</div>
<h1 class="title toc-ignore">AAAR 2023 Data Wrangling Tutorial</h1>
<h4 class="author">Dr. Naomi Zimmerman</h4>
<h4 class="date">2023-10-02</h4>
</div>
<div id="introduction" class="section level1">
<h1>Introduction</h1>
<p>Managing your experimental data is increasingly difficult because of
the sheer volume of data that is being collected, the high time
resolution of the data, the number of data users, and publishing
requirements on making data and codes open and accessible. Taking some
time to learn from core data management and data wrangling skills is
important!</p>
<p>In this tutorial, we’ll look at the data management and analysis
pipeline from data import / upload through to data visualization. We’ll
compare a couple of different approaches considering the needs I just
outlined. The first data set I am providing is a pre-cleaned data set
for simplicity and to show the pipeline from start to finish. If we have
time, we’ll look at a more complicated set of data that requires more
pre-processing before we can look at it.</p>
<p>There are many coding languages you can use to work with your data.
In this tutorial, I am going to use Structured Query Language (SQL) and
R. To manage SQL data, I will show an example with <a
href="https://www.mysql.com/products/community/">MySQL</a>. This is just
one database management system, and many of the same principles will
apply if you’re using other popular SQL database management systems like
<a href="https://www.sqlite.org/download.html">SQLite</a> or <a
href="https://www.postgresql.org/download/">PostgreSQL</a>. You just
need to change the R package you are using to interface with the SQL
database management system you are using.</p>
<p>I’ll also briefly demonstrate importing your data directly into <a
href="https://cran.r-project.org/">R</a> and some common pitfalls / why
the SQL approach can be preferable.</p>
<p>Once our data is in <a href="https://cran.r-project.org/">R</a> using
<a href="https://posit.co/download/rstudio-desktop/">RStudio</a>, a
popular integrated development environment (IDE) for R, we’ll do some
quick visualizations, introducing you to a popular collection of R
coding packages called the <a
href="https://www.tidyverse.org/">‘tidyverse’</a>. This shares many
principles with the <a href="https://pandas.pydata.org/">‘pandas’</a>
software library in <a
href="https://www.python.org/downloads/">Python</a>. So while we will
work in R/RStudio today, again, many of the ideas or processes can be
replicated in Python (for example using the <a
href="https://www.jetbrains.com/pycharm/download/">PyCharm IDE</a>).
It’s just a matter of personal preference :)</p>
<p>To manage our R codes and take notes / share interim plots, we’ll be
using a markdown file. I’m typing this tutorial right now in an R
Markdown file. Very meta. Another popular piece of software for markdown
files with embedded R or Python coding is <a
href="https://jupyter.org/">Jupyter Notebooks</a>. We won’t run any
Jupyter notebooks, but I will show you briefly what they’re all
about.</p>
<p>As we work through our data, we all know that analysis can take time.
Or perhaps we want to run a code that might break everything (happens to
the best of us!) and we want to make sure we can restore our previous
code. Version control is your friend here and it’s so easy to do with <a
href="https://git-scm.com/downloads">Git</a>, which is a distributed
version control system that tracks changes in any set of computer files.
We’ll use the <a href="https://github.com/join">Github</a> platform as
our convenient cloud-based system to execute our Git version control. A
nice feature of Github is that we can also easily convert our Markdown
files into webpages (which is what you’re reading right now!). So cool,
right?</p>
<p>Lastly, if you have a lot of data being collected routinely, it can
be cool to show your data. We’ll do a simple example in <a
href="https://grafana.com/grafana/download">Grafana</a>, which is an
open source analytics and interactive visualization web application.</p>
<p>What we’ll cover today is a lot for a 1 hour 45 minute session - and
that’s okay! The goal is that you come out of this tutorial with some
ideas, new terminology and an interest in learning more. If you take the
time to learn these principles and approaches early on in your program,
you’ll have an easier time down the road when you’re trying to address
Reviewer 2 comments almost a year after a paper was originally
developed, because you left yourself an awesome paper trail. Future you
is already thanking you! Now without further ado, let’s get started.</p>
<div id="getting-yourself-set-up" class="section level2">
<h2>Getting yourself set-up</h2>
<p>If you want to follow along in real-time, you’ll need the following
tools installed on your machine. Note that I tested this tutorial in the
Windows operating system. I can’t make any guarantees it will work 100%
smoothly in a macOS or Linux operating system, but there shouldn’t be
too many pitfalls with this.</p>
<p>Tools needed:</p>
<ul>
<li>MySQL <a href="https://www.youtube.com/watch?v=qBBXBZXKi0w">(Click
here for YouTube tutorial for installing MySQL on Windows 11)</a></li>
<li>R and RStudio <a
href="https://www.youtube.com/watch?v=YrEe2TLr3MI">(Click here for
YouTube tutorial for installing R and RStudio)</a></li>
<li>Git and a Github account <a
href="https://github.com/git-guides/install-git">(Click here for a
Github Guide on Installing Git)</a></li>
<li>Connect Git to RStudio <a
href="https://www.youtube.com/watch?v=bUoN85QvC10">(Click here for a
YouTube tutorial on connecting Git and Github to an RStudio
Project)</a></li>
</ul>
<p>Other notes:</p>
<ul>
<li>This tutorial will require a bunch of R packages to be installed -
but don’t worry, I have parts of the code blocks below that will install
any R packages you might need that you don’t already have :)</li>
<li>All the data, codes and markdown files are available in the Github
repository <a
href="https://github.com/nzimmerman-ubc/AAAR2023-tutorial">(Click here
to access)</a></li>
<li>If you just want the R Markdown file, you can download it from the
upper right corner of the page.</li>
</ul>
</div>
</div>
<div id="part-0-version-control" class="section level1">
<h1>Part 0: Version Control</h1>
<p>In developing this tutorial, I used version control using Git and
Github. If you’re in academia, Github is great because you can get
access to many paid features for free (making pages from private
repositories, creating organizations, etc.). You can interact with Git
in RStudio very easily after it’s installed (see links from the
Introduction). Once you’ve successfully installed Git and made it
accessible in RStudio, you’ll see a little “Git” tab in the top right
panel. We can use this panel to quickly Commit changes to our
repository, view file additions or deletions, etc.</p>
<p>Those who are familiar with Git may prefer to use the command line -
that’s outside of the scope of our tutorial today, but you can access
the terminal from RStudio in the “Terminal” tab of the bottom left
panel.</p>
<p>I will now quickly demonstrate making a change, committing that
change, and pushing my change to Github.</p>
<div id="forking-the-directory" class="section level2">
<h2>Forking the directory</h2>
<p>If you want to follow along in real-time with this tutorial, navigate
to this tutorial’s repository <a
href="https://github.com/nzimmerman-ubc/AAAR2023-tutorial">(Click here
to access)</a> and create a fork (which will create a local copy in your
own repository).</p>
</div>
</div>
<div id="part-1-sql-set-up-and-logistics" class="section level1">
<h1>Part 1: SQL Set-up and Logistics</h1>
<p>Before we can start playing with data, we’re going to make sure we
have set up and configured MySQL on our machine. We’ll do this part
live, so follow along. We can interact with MySQL in a few ways:</p>
<ul>
<li>MySQL Workbench: A Graphical User Interface for your SQL data</li>
<li>The command line</li>
</ul>
<p>The nice thing about the workbench is that it can help you learn how
to write and parse SQL queries, since it will translate your request
into the query. So we’ll mostly be using the Workbench to check that our
work is being stored correctly, but I will show some quick examples in
the command line too later on in the tutorial.</p>
<p>Once we have set up MySQL on our machine, making note of the MySQL
user (and their credentials to write new tables etc.), we can start
working in R to import our data, write it to SQL, and be off to the
races.</p>
<p><em>A note on how I’m using SQL here:</em> One of the core features
of an SQL database is that you can link different scheme (think tables)
together with keys. Keys can be used to create a relationship among
different database tables or views. This isn’t a tutorial on SQL, so
we’re keeping it simple today. But if SQL is something you want to
learn, this is a pretty fundamental concept to keep in mind.</p>
<div id="diving-into-r" class="section level2">
<h2>Diving into R</h2>
<p>What you’re looking at right now is an HTML version of an RMarkdown
file that I prepared for this tutorial. A markdown document allows me to
combine text, code blocks, and outputs of those codes in one place. If
you download the ‘Rmd’ file from the website, you can see what the
Markdown document looks like in its raw form. When you’re done editing,
you can see the formatted html version by “Knitting”.</p>
<div id="an-aside-jupyter-notebooks" class="section level3">
<h3>(<em>An Aside</em>) Jupyter Notebooks</h3>
<p>A very popular alternative to R Markdown documents is Jupyter
Notebooks. If Python is your thing, you’ll probably prefer them. You can
also add in R to Jupyter notebooks and even toggle between R code blocks
and Python code blocks in one place. Let’s take a quick peek at the
Jupyter notebooks ecosystem so you can make a mental note to learn more
another day.</p>
</div>
<div id="r-set-up-libraries-and-packages" class="section level3">
<h3>R Set-up: Libraries and Packages</h3>
<p>In this first code block, we’re going to (1) check for the necessary
packages to execute the codes in this Markdown document, (2) install
those packages if you haven’t already installed them, and (3) load the
packages if installed.</p>
<p>I like the ‘pacman’ package to streamline this process, since you can
just give it a list of packages within the ‘p_load’ command that will
elegantly install any missing packages and then load them.</p>
<pre class="r"><code># Check for pacman and load
if (!require("pacman")) install.packages("pacman"); library(pacman)</code></pre>
<pre><code>## Loading required package: pacman</code></pre>
<pre class="r"><code># Install / load required packages
p_load(DBI,RODBC,odbc,dbplyr,RMySQL,tidyverse,keyring,con2aqi,lubridate, stringr)</code></pre>
</div>
<div id="r-set-up-sql-connection" class="section level3">
<h3>R Set-up: SQL Connection</h3>
<p>The packages we have loaded (specifically: DBI, RODBC, ODBC and
dbplyr) will let us connect to and manipulate an SQL database. Let’s
first check to make sure we have the appropriate drivers installed to
run these packages successfully, and then connect to our SQL
database.</p>
<p>(note, if you don’t have an empty database to work with, we can
create one in either the MySQL workbench or in the command line)</p>
<blockquote>
<p>mysql -u root -p</p>
</blockquote>
<blockquote>
<p>CREATE DATABASE livedemo;</p>
</blockquote>
<p>You’ll notice in the code block below that I haven’t actually shown
you my MySQL password - this is good coding practice. It’s not a good
idea to be widely sharing passwords, API keys etc. The best approach
here is to store your password as an environment variable. I like the
‘keyring’ package to do this for me. I have previously stored my
password and so I can just use the key_get function to load it.
Hooray!</p>
<pre class="r"><code># First check that the MySQL driver is listed here before proceeding.
sort(unique(odbcListDrivers()[[1]]))</code></pre>
<pre><code>## [1] "Microsoft Access Driver (*.mdb, *.accdb)"
## [2] "Microsoft Access Text Driver (*.txt, *.csv)"
## [3] "Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)"
## [4] "MySQL ODBC 8.1 ANSI Driver"
## [5] "MySQL ODBC 8.1 Unicode Driver"
## [6] "SQL Server"</code></pre>
<pre class="r"><code># Now connect to our SQL database using the 'dbConnect' function:
sql_conn <- dbConnect(RMySQL::MySQL(),
dbname = "aaar2023tutorial",
Server = "localhost",
port = 3306,
user = "root",
password = key_get("MYSQL_PASSWORD")
)</code></pre>
</div>
</div>
</div>
<div id="part-2-building-our-sql-database-and-querying-it-example-1"
class="section level1">
<h1>Part 2: Building our SQL Database and Querying it; Example 1</h1>
<p>In our first example, we have some pre-cleaned data from a deployment
last year in Vancouver, BC. In this deployment, we had 11
multi-pollutant low-cost sensors, and also collected data from 4
regulatory monitoring stations to compare our focus neighborhood to the
surrounding region. Let’s load the metadata from this example and show
it as a table.</p>
<pre class="r"><code>metadata <- read_csv("data/example 1/metadata.csv", show_col_types = FALSE)
knitr::kable(metadata)</code></pre>
<table>
<colgroup>
<col width="38%" />
<col width="26%" />
<col width="8%" />
<col width="12%" />
<col width="14%" />
</colgroup>
<thead>
<tr class="header">
<th align="left">Type</th>
<th align="left">Name</th>
<th align="left">ID</th>
<th align="right">latitude</th>
<th align="right">longitude</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1001</td>
<td align="left">R1001</td>
<td align="right">49.2840</td>
<td align="right">-123.0970</td>
</tr>
<tr class="even">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1002</td>
<td align="left">R1002</td>
<td align="right">49.2810</td>
<td align="right">-123.1010</td>
</tr>
<tr class="odd">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1004</td>
<td align="left">R1004</td>
<td align="right">49.2790</td>
<td align="right">-123.0850</td>
</tr>
<tr class="even">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1005</td>
<td align="left">R1005</td>
<td align="right">49.2780</td>
<td align="right">-123.0910</td>
</tr>
<tr class="odd">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1008</td>
<td align="left">R1008</td>
<td align="right">49.2770</td>
<td align="right">-123.0860</td>
</tr>
<tr class="even">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1009</td>
<td align="left">R1009</td>
<td align="right">49.2810</td>
<td align="right">-123.0740</td>
</tr>
<tr class="odd">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1011</td>
<td align="left">R1011</td>
<td align="right">49.2790</td>
<td align="right">-123.0920</td>
</tr>
<tr class="even">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1012</td>
<td align="left">R1012</td>
<td align="right">49.2820</td>
<td align="right">-123.0990</td>
</tr>
<tr class="odd">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1039</td>
<td align="left">R1039</td>
<td align="right">49.2800</td>
<td align="right">-123.0930</td>
</tr>
<tr class="even">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1040</td>
<td align="left">R1040</td>
<td align="right">49.2800</td>
<td align="right">-123.0820</td>
</tr>
<tr class="odd">
<td align="left">Low-cost sensor</td>
<td align="left">RAMP 1041</td>
<td align="left">R1041</td>
<td align="right">49.2820</td>
<td align="right">-123.0880</td>
</tr>
<tr class="even">
<td align="left">Regulatory Metro Vancouver</td>
<td align="left">Burnaby South</td>
<td align="left">BS</td>
<td align="right">49.2152</td>
<td align="right">-122.9857</td>
</tr>
<tr class="odd">
<td align="left">Regulatory Metro Vancouver</td>
<td align="left">Burnaby Kensington</td>
<td align="left">BK</td>
<td align="right">49.2792</td>
<td align="right">-122.9707</td>
</tr>
<tr class="even">
<td align="left">Regulatory Metro Vancouver</td>
<td align="left">Richmond South</td>
<td align="left">RS</td>
<td align="right">49.1414</td>
<td align="right">-123.1082</td>
</tr>
<tr class="odd">
<td align="left">Regulatory Metro Vancouver</td>
<td align="left">Mahon Park</td>
<td align="left">MP</td>
<td align="right">49.3240</td>
<td align="right">-123.0835</td>
</tr>
</tbody>
</table>
<p>For each of these locations, I have provided about 4 months of daily
average concentrations of NO<sub>2</sub>, PM<sub>2.5</sub>, and
O<sub>3</sub>. I want to first create some SQL tables to store this
data, load the data into those tables, and then use the SQL query format
to start making some analyses and figures.</p>
<div id="load-the-data-and-create-the-tables" class="section level2">
<h2>Load the data and create the tables</h2>
<p>Note I have put in a flag here of 0 or 1 if this is your first time
executing the script. If you’re running it for the first time, set
initial_run to “1”, otherwise set it to “0” to skip to the next steps.
SQL will throw an error if you try and create a new table that already
exists.</p>
<p>We also need to set some permissions on the R and MySQL side of
things to make sure we can write from these local files. For these
permissions in R, this is embedded in the code. For the MySQL side, you
will need to edit the “my.ini” configuration file using Notepad or other
text editor and add the statement “local_infile=1” under the [client],
[mysql], and [mysqld] sections of the file and save it. I’ll show you
this now.</p>
<pre class="r"><code>initial_run=0
if(initial_run==1){
## This should only be run once.
# Load our data
NO2_daily <- read_csv("data/example 1/NO2_daily.csv", col_types = cols(date = col_date(format = "%m/%d/%Y")), show_col_types = FALSE)
O3_daily <- read_csv("data/example 1/O3_daily.csv", col_types = cols(date = col_date(format = "%m/%d/%Y")), show_col_types = FALSE)
PM_daily <- read_csv("data/example 1/PM_daily.csv", col_types = cols(date = col_date(format = "%m/%d/%Y")), show_col_types = FALSE)
# So that we can permit writing to SQL from R!
dbSendQuery(sql_conn, "SET GLOBAL local_infile = true;")
# create tables in your SQL database
dbCreateTable(sql_conn,name="no2_daily", fields=NO2_daily)
dbCreateTable(sql_conn,name="o3_daily", fields=O3_daily)
dbCreateTable(sql_conn,name="pm_daily", fields=PM_daily)
# write our data to the SQL database
dbWriteTable(sql_conn,"no2_daily",NO2_daily,append=TRUE, row.names=FALSE)
dbWriteTable(sql_conn,"o3_daily",O3_daily,append=TRUE, row.names=FALSE)
dbWriteTable(sql_conn,"pm_daily",PM_daily,append=TRUE, row.names=FALSE)
# RMySQL has some quirks where it really fights pushing the data in a correct datetime format, so we manually send a query to SQL to make sure it's formatted correctly!
dbSendQuery(sql_conn,"ALTER TABLE no2_daily MODIFY date datetime;")
dbSendQuery(sql_conn,"ALTER TABLE o3_daily MODIFY date datetime;")
dbSendQuery(sql_conn,"ALTER TABLE pm_daily MODIFY date datetime;")
}</code></pre>
</div>
<div id="interacting-with-the-data" class="section level2">
<h2>Interacting with the data</h2>
<p>Imagine now that you are perhaps a secondary user of the data - maybe
this is from a big field campaign and different people will be slicing
and dicing the data in different ways. This is where having your data in
an SQL database can be super helpful.</p>
<p>You can have a select group of folks maintaining the SQL database (or
even better log directly into an SQL server, but that’s a story for
another day), and then create a new user who only has permission to
SELECT data from the SQL database but not actually modify it.</p>
<p>That keeps your original data safe and sound! Also it’s
computationally more efficient to just pull in the data you need.</p>
<p>So let’s look at how we can do this in R. To do this, we’re going to
take advantage of the ‘dbplyr’ package, which lets you use typically
‘tidyverse’ style commands to interact with databases. Once you’ve
finished your tweaks, the `dbplyr’ package will just make 1 singular
call to the database, and it also has the functionality to show you your
query so you can learn the SQL equivalent at the same time.
Win-win!!</p>
<p>I will show you three different ways of playing with some of this
data:</p>
<ol style="list-style-type: decimal">
<li><p>Pulling all the pollutant data into one data.table in R for a
specified week at the Mahon Park site and calculating a pseudo-AQI (my
time averaging is wrong for true AQI, but this is a fictional example).
There is a little package called con2aqi that converts concentrations to
AQI that we will use here.</p></li>
<li><p>Box plots across all our sites for each pollutant</p></li>
<li><p>A time series of all our sites for NO2.</p></li>
</ol>
<p>These are just some simple examples, obviously everyone’s data
questions are unique, this is just to provide some inspiration.</p>
<pre class="r"><code># Data processing 1: Let's say we are interested in calculating the AQI for the week of May 15 - 21, 2022 at the Mahon Park site (MP)
no2_db = tbl(sql_conn,"no2_daily") %>% select(date,MP) %>% filter(between(date, as.Date('2022-05-15'), as.Date('2022-05-21'))) %>% show_query() %>% collect() %>% rename(NO2_MP = MP)</code></pre>
<pre><code>## <SQL>
## SELECT `date`, `MP`
## FROM `no2_daily`
## WHERE (`date` BETWEEN CAST('2022-05-15' AS DATE) AND CAST('2022-05-21' AS DATE))</code></pre>
<pre class="r"><code>o3_db = tbl(sql_conn,"o3_daily") %>% select(date,MP) %>% filter(between(date, as.Date('2022-05-15'), as.Date('2022-05-21'))) %>% show_query() %>% collect() %>% rename(O3_MP = MP)</code></pre>
<pre><code>## <SQL>
## SELECT `date`, `MP`
## FROM `o3_daily`
## WHERE (`date` BETWEEN CAST('2022-05-15' AS DATE) AND CAST('2022-05-21' AS DATE))</code></pre>
<pre class="r"><code>pm_db = tbl(sql_conn,"pm_daily") %>% select(date,MP) %>% filter(between(date, as.Date('2022-05-15'), as.Date('2022-05-21'))) %>% show_query() %>% collect() %>% rename(PM_MP = MP)</code></pre>
<pre><code>## <SQL>
## SELECT `date`, `MP`
## FROM `pm_daily`
## WHERE (`date` BETWEEN CAST('2022-05-15' AS DATE) AND CAST('2022-05-21' AS DATE))</code></pre>
<pre class="r"><code>#let's put it together into one dataframe for our local analysis
aqi <- left_join(no2_db, o3_db, by='date') %>% left_join(., pm_db, by='date') %>% rowwise() %>%
mutate(aqi = max(con2aqi("pm25",PM_MP),con2aqi("o3",O3_MP/1000,"8h"),con2aqi("no2",NO2_MP)))
knitr::kable(aqi)</code></pre>
<table>
<thead>
<tr class="header">
<th align="left">date</th>
<th align="right">NO2_MP</th>
<th align="right">O3_MP</th>
<th align="right">PM_MP</th>
<th align="right">aqi</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">2022-05-15 00:00:00</td>
<td align="right">17.36167</td>
<td align="right">23.96840</td>
<td align="right">3.784572</td>
<td align="right">23</td>
</tr>
<tr class="even">
<td align="left">2022-05-16 00:00:00</td>
<td align="right">18.65333</td>
<td align="right">39.14375</td>
<td align="right">4.175584</td>
<td align="right">37</td>
</tr>
<tr class="odd">
<td align="left">2022-05-17 00:00:00</td>
<td align="right">7.83000</td>
<td align="right">35.28208</td>
<td align="right">4.057679</td>
<td align="right">33</td>
</tr>
<tr class="even">
<td align="left">2022-05-18 00:00:00</td>
<td align="right">8.46000</td>
<td align="right">36.90521</td>
<td align="right">2.723355</td>
<td align="right">35</td>
</tr>
<tr class="odd">
<td align="left">2022-05-19 00:00:00</td>
<td align="right">16.86000</td>
<td align="right">31.18792</td>
<td align="right">2.832343</td>
<td align="right">29</td>
</tr>
<tr class="even">
<td align="left">2022-05-20 00:00:00</td>
<td align="right">15.44333</td>
<td align="right">27.66354</td>
<td align="right">4.070064</td>
<td align="right">26</td>
</tr>
<tr class="odd">
<td align="left">2022-05-21 00:00:00</td>
<td align="right">23.57333</td>
<td align="right">27.47411</td>
<td align="right">5.322663</td>
<td align="right">26</td>
</tr>
</tbody>
</table>
<pre class="r"><code>##################
# Data processing 2: Make box plots of the NO2, O3 and PM2.5 daily average concentrations across all the sites.
no2_tidy = tbl(sql_conn,"no2_daily") %>% select(-date) %>% collect() %>% pivot_longer(everything(),names_to = "site", values_to = "concentration")
# Create a custom order for the 'site' variable
site_order <- c("BS", "BK", "MP","RS","R1001","R1002","R1004","R1005","R1008","R1009","R1011","R1012","R1039","R1040","R1041")
# Generate the boxplot in ggplot2
no2_plot <- ggplot(no2_tidy, aes(x = factor(site, levels = site_order), y = concentration, fill=site)) +
geom_boxplot() +
labs(title = "NO2 Concentrations by Site",
x = "Site",
y = "Concentration (ppb)") +
theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") +
scale_fill_discrete() +
coord_cartesian(ylim = c(0,60))
no2_plot</code></pre>
<p><img src="index_files/figure-html/ex1-query-1.png" width="672" /></p>
<pre class="r"><code># Repeat for O3
o3_tidy = tbl(sql_conn,"o3_daily") %>% select(-date) %>% collect() %>% pivot_longer(everything(),names_to = "site", values_to = "concentration")
o3_plot <- ggplot(o3_tidy, aes(x = factor(site, levels = site_order), y = concentration, fill=site)) +
geom_boxplot() +
labs(title = "O3 Concentrations by Site",
x = "Site",
y = "Concentration (ppb)") +
theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") +
scale_fill_discrete() +
coord_cartesian(ylim = c(0,60))
o3_plot</code></pre>
<p><img src="index_files/figure-html/ex1-query-2.png" width="672" /></p>
<pre class="r"><code># Repeat for PM2.5
pm_tidy = tbl(sql_conn,"pm_daily") %>% select(-date) %>% collect() %>% pivot_longer(everything(),names_to = "site", values_to = "concentration")
pm_plot <- ggplot(pm_tidy, aes(x = factor(site, levels = site_order), y = concentration, fill=site)) +
geom_boxplot() +
labs(title = "PM2.5 Concentrations by Site",
x = "Site",
y = "Concentration (ug/m3)") +
theme(axis.text.x = element_text(angle = 90, hjust = 1), legend.position="none") +
scale_fill_discrete() +
coord_cartesian(ylim = c(0,20))
pm_plot</code></pre>
<p><img src="index_files/figure-html/ex1-query-3.png" width="672" /></p>
<pre class="r"><code># Date Processing 3: Now let's make a time series for the month of July 2022 for NO2 at all of our sites.
no2_july = tbl(sql_conn,"no2_daily") %>% filter(month(date)==7) %>% show_query() %>% collect() %>% pivot_longer(cols=c(2:16),names_to = "site", values_to = "concentration")</code></pre>
<pre><code>## <SQL>
## SELECT *
## FROM `no2_daily`
## WHERE (EXTRACT(month FROM `date`) = 7.0)</code></pre>
<pre class="r"><code>no2_july$Grouping <- as.factor(no2_july$site)
ggplot(no2_july, aes(x=ymd_hms(date), y=concentration, color=Grouping)) +
geom_line(size=2, na.rm=TRUE) +
labs(title = "Time Series of Data for July",
x = "Date",
y = "NO2 Concentration (ppb)") +
scale_color_manual(values = rainbow(15), breaks = site_order) +
theme_minimal()</code></pre>
<p><img src="index_files/figure-html/ex1-query-4.png" width="672" /></p>
</div>
</div>
<div id="part-3-dashboards-and-plotting-in-grafana"
class="section level1">
<h1>Part 3: Dashboards and plotting in Grafana</h1>
<p>Some of the figures we just generated are fine, or might be useful
for a publication, but say we are routinely collecting and downloading
data and we want to track our data as it is coming in (maybe we are
routinely collecting data and want a quick / dynamic way to visualize).
We can leverage our same SQL databases into the open-source Grafana
dashboarding tool. Let’s check it out!</p>
<div id="create-a-read-only-user-in-mysql-to-interface-with-grafana"
class="section level2">
<h2>Create a read-only user in MySQL to interface with Grafana</h2>
<p>There’s no reason Grafana needs to be able to write new data, it’s
just visualizing what we already collected, so let’s make a restricted
version.</p>
<blockquote>
<p>CREATE USER ‘grafana-demo’@‘localhost’ IDENTIFIED BY
‘aaartutorial’;</p>
</blockquote>
<blockquote>
<p>SELECT User from mysql.user;</p>
</blockquote>
<blockquote>
<p>GRANT SELECT ON database_name.table_name TO
‘username’@‘localhost’;</p>
</blockquote>
<blockquote>
<p>FLUSH PRIVILEGES;</p>
</blockquote>
<p>Now let’s hop on over to Grafana and see what we can do. In general
this will consist of:</p>
<ul>
<li>Connecting to our MySQL data source (just a one time thing)</li>
<li>Creating new panels for our dashboard either using SQL Query or with
their interactive code builder.</li>
</ul>
</div>
</div>
<div id="part-4-some-messier-data" class="section level1">
<h1>Part 4: Some messier data</h1>
<p>Now let’s imagine we have some data as it is outputted directly from
an instrument. Let’s go with a WCPC for example. In our example 2 data
folder, we have 5 separate csv files from 5 different days, and the data
doesn’t start cleanly. Let’s process this to concatenate the files and
extract the relevant stuff!</p>
<div id="load-the-data-and-choose-column-names-we-like"
class="section level2">
<h2>Load the data and choose column names we like</h2>
<pre class="r"><code># First get the names of all the files in our WCPC raw folder:
file_names <- list.files(path = "data/example 2/WCPC raw/", pattern = "*.csv", full.names = TRUE)
# Use lapply to read and concatenate the data
data_list <- lapply(file_names, function(file) {
read.csv(file, skip = 16)
})
# Combine the list of data frames into one data frame using bind_rows
concatenated_cpc <- bind_rows(data_list)
# Give the columns nicer names
new_names <- c("datetime", "elapsed", "concentration", "counts", "error_code")
names(concatenated_cpc) <- new_names
#Clean up any blank rows lingering around from the csv:
concatenated_cpc <- concatenated_cpc %>%
filter(datetime != "" & !is.na(datetime))
knitr::kable(head(concatenated_cpc))</code></pre>
<table>
<thead>
<tr class="header">
<th align="left">datetime</th>
<th align="right">elapsed</th>
<th align="right">concentration</th>
<th align="right">counts</th>
<th align="left">error_code</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">2023-09-13 0:00:00</td>
<td align="right">116245</td>
<td align="right">4043.41</td>
<td align="right">20570</td>
<td align="left">NA</td>
</tr>
<tr class="even">
<td align="left">2023-09-13 0:00:01</td>
<td align="right">116246</td>
<td align="right">4087.23</td>
<td align="right">20790</td>
<td align="left">NA</td>
</tr>
<tr class="odd">
<td align="left">2023-09-13 0:00:02</td>
<td align="right">116247</td>
<td align="right">4137.68</td>
<td align="right">21043</td>
<td align="left">NA</td>
</tr>
<tr class="even">
<td align="left">2023-09-13 0:00:03</td>
<td align="right">116248</td>
<td align="right">3999.69</td>
<td align="right">20350</td>
<td align="left">NA</td>
</tr>
<tr class="odd">
<td align="left">2023-09-13 0:00:04</td>
<td align="right">116249</td>
<td align="right">4133.54</td>
<td align="right">21022</td>
<td align="left">NA</td>
</tr>
<tr class="even">
<td align="left">2023-09-13 0:00:05</td>