-
Notifications
You must be signed in to change notification settings - Fork 3
/
coding.html
970 lines (859 loc) · 35.3 KB
/
coding.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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Week 2. More Git + Better Coding Practices</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/readable.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-9.12.0/textmate.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<script src="site_libs/kePrint-0.0.1/kePrint.js"></script>
<link href="site_libs/font-awesome-5.1.0/css/all.css" rel="stylesheet" />
<link href="site_libs/font-awesome-5.1.0/css/v4-shims.css" rel="stylesheet" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<link rel="stylesheet" href="styles.css" type="text/css" />
<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%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 66px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 71px;
margin-top: -71px;
}
.section h2 {
padding-top: 71px;
margin-top: -71px;
}
.section h3 {
padding-top: 71px;
margin-top: -71px;
}
.section h4 {
padding-top: 71px;
margin-top: -71px;
}
.section h5 {
padding-top: 71px;
margin-top: -71px;
}
.section h6 {
padding-top: 71px;
margin-top: -71px;
}
.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: #ffffff;
}
.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>
// 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>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
background: white;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
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: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.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">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.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;
}
.tocify .list-group-item {
border-radius: 0px;
}
.tocify-subheader {
display: inline;
}
.tocify-subheader .tocify-item {
font-size: 0.95em;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- 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">RWorkflow</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="set-up.html">
<span class="fa fa-clone"></span>
Set-up
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class="fa fa-cogs"></span>
Coding
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="rstudio.html">
<span class="fa fa-cogs"></span>
Week 1 RStudio + Version Control
</a>
</li>
<li>
<a href="coding.html">
<span class="fa fa-code"></span>
Week 2 Object oriented structure
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class="fa fa-git"></span>
Git
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="rstudio.html">
<span class="fa fa-cogs"></span>
Week 1 Intro to Git
</a>
</li>
<li>
<a href="coding.html">
<span class="fa fa-github"></span>
Week 2 More Git + GitHub
</a>
</li>
<li>
<a href="websites.html">
<span class="fa fa-chrome"></span>
Websites with GitHub
</a>
</li>
<li>
<a href="jekyll.html">
<span class="fa fa-sitemap"></span>
Dynamic Websites with Jekyll and GitHub
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class="fa fa-file"></span>
RMarkdown
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="RMarkdown.html">
<span class="fa fa-file"></span>
Week 3 R Markdown for Reports
</a>
</li>
<li>
<a href="bookdown.html">
<span class="fa fa-book"></span>
Bookdown
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class="fa fa-archive"></span>
R Packages
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="packages.html">
<span class="fa fa-archive"></span>
Week 4 R Packaging with RStudio
</a>
</li>
<li>
<a href="roxygen.html">
<span class="fa fa-question-circle"></span>
Week 5 Roxygen documentation
</a>
</li>
<li>
<a href="shiny.html">
<span class="fa fa-gamepad"></span>
Shiny GUIs
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
More
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="links.html">Tutorials</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/RVerse-Tutorials/RWorkflow-NWFSC-2020">
<span class="fa fa-github"></span>
Repo
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Week 2. More Git + Better Coding Practices</h1>
</div>
<table class="table" style="margin-left: auto; margin-right: auto;">
<tbody>
<tr>
<td style="text-align:left;color: white !important;background-color: blue !important;width: 20%; ">
Compartmentalized
</td>
<td style="text-align:left;color: white !important;background-color: blue !important;width: 20%; ">
Documented
</td>
<td style="text-align:left;color: white !important;background-color: blue !important;width: 20%; ">
Extendible
</td>
<td style="text-align:left;color: white !important;background-color: blue !important;width: 20%; ">
Reproducible
</td>
<td style="text-align:left;color: white !important;background-color: blue !important;width: 20%; ">
Robust
</td>
</tr>
</tbody>
</table>
<div id="overview" class="section level1">
<h1>Overview</h1>
<p>This week I will cover more Git topics and basic coding habits that I have learned over the years. These are good habits that will help make your code less buggy and easier to extend.</p>
<p>Git, GitHub, GitLab</p>
<ul>
<li>How to clone someone else’s GitHub or GitLab repository</li>
<li>How to clone your own repository–when you want to make a copy and use that as a template for something new.</li>
<li>What are branches, merge conflicts and pull requests?</li>
<li>Fork or clone? What’s the difference?</li>
<li>How to add Git to an existing RStudio project and get that on GitHub or GitLab.</li>
</ul>
<p>Coding Tips</p>
<ul>
<li>How to organize and plan your code and why adopting an ‘object-oriented mindset’ will help your code organization (regardless of whether you use object-oriented coding)</li>
<li>What are namespaces and why you should use <code>::</code> to call functions.</li>
<li>Tips on writing code and functions in R - little things that will make your code better and more robust</li>
<li>Tips on things to avoid in your R code, i.e. quirks of R that will tend to create bugs</li>
</ul>
<p>The material I’m presenting geared toward those who have done a bit of R programming but work mainly with scripts or with functions just for their own use. For new programmers, I recommend <a href="https://www.amazon.com/R-Student-Companion-Brian-Dennis-ebook/dp/B009AIU07G">The R Student Companion</a> -> <a href="https://r4ds.had.co.nz/">R for Data Science</a> -> books specific to your work.</p>
<div id="downloading-other-peoples-repositories" class="section level2">
<h2>Downloading other people’s repositories</h2>
<p>There are two easy ways to do this. Use the one that seems more logical to you.</p>
<p>Method 1.</p>
<ol style="list-style-type: decimal">
<li>In a browser, go to the GitHub (or GitLab) repository you want to copy.</li>
<li>Copy its url.</li>
<li>Open GitHub or GitLab.<br />
</li>
<li>If using GitHub, click the <code>+</code> in top right and click <code>import repository</code>. Paste in the url and give your repo a name.</li>
<li>If using GitLab, click <code>New Project</code> on right, then <code>Import Repository</code> tab, then click <code>Repo by URL</code>. Paste in url and give repo a name.</li>
<li>Open RStudio and click the project tab in the top right and select, <code>New Project</code>. Then select <code>Version Control</code> and paste in the url of <strong>your</strong> repository’s url. For example, <code>https://github.com/<youraccount>/Test</code><br />
</li>
<li>Add the new repo to GitHub Desktop. Open GitHub Desktop, select File>Add Local Repository and navigate to the folder with the new repository.</li>
</ol>
<p>Method 2.</p>
<p>Steps 1-4 are the same but you can swap step 5 and 6.</p>
<ol start="5" style="list-style-type: decimal">
<li>Open GitHub Desktop. Select File>Clone Repository. Paste in the repository url that you are copying and tell it where to save the repository.</li>
<li>Open RStudio and click the project tab in the top right and select, <code>New Project</code>. Then select <code>Existing Directory</code> and navigate to the directory where you just saved the repo.</li>
</ol>
<p>You can also clone someone elses repo directly into RStudio or GitHub Desktop and then “Publish” to GitHub or GitLab. I am not going to show that but I show that on this <a href="Git-RStudio.html">page</a>. For GitLab, it will require issuing Git commands from a terminal. Note, in my experience, method 1 or 2 above is the way to avoid Git-misery as a Git beginner.</p>
</div>
<div id="making-a-copy-of-your-own-repository" class="section level2">
<h2>Making a copy of your own repository</h2>
<p>Let say you want to make a copy of a repository and use it as a template to make something else. And you don’t want the history!</p>
<ol style="list-style-type: decimal">
<li>Make a blank repo on GitHub or GitLab (add that Readme file)</li>
<li>Pull that down to your computer</li>
<li>Copy the repo you want to copy into the new repo folder but <strong>do not copy the .git folder</strong>. Remember the <code>.git</code> folder is hidden.</li>
</ol>
</div>
</div>
<div id="code-organization" class="section level1">
<h1>Code Organization</h1>
<div id="r-is-object-oriented" class="section level2">
<h2>R is object oriented</h2>
<p>Run this code.</p>
<pre class="r"><code>fit <- lm(dist ~ speed, data=cars)
class(fit)</code></pre>
<pre><code>## [1] "lm"</code></pre>
<p>“lm” is the class of the object “fit”. R <em>knows</em> things to do with objects of class “lm”.</p>
<pre class="r"><code>coef(fit)</code></pre>
<pre><code>## (Intercept) speed
## -17.579095 3.932409</code></pre>
<p>It did that because there is a function <code>coef.lm</code> and R looks for that to see what to do when you pass a “lm” object to <code>coef()</code>.</p>
<p>All object of class “lm” are a list with a standard set of items in that list:</p>
<pre class="r"><code>names(fit)</code></pre>
<pre><code>## [1] "coefficients" "residuals" "effects" "rank"
## [5] "fitted.values" "assign" "qr" "df.residual"
## [9] "xlevels" "call" "terms" "model"</code></pre>
<p>That information contains all the information about the fit, the data used for the fit, and the call to <code>lm()</code>. We can just pass <code>fit</code> to <code>print()</code>, <code>plot()</code>, <code>summary()</code>, etc. I could write a new function, <code>foo.lm</code>, to do something new with a “lm” object.</p>
<p>In the call to <code>lm</code>, we had another object, <code>saldat</code>. <code>saldat</code> is class <code>data.frame</code>. <code>lm()</code> knows what to do with data that is a data frame.</p>
</div>
<div id="object-oriented-mindset" class="section level2">
<h2>Object-oriented mindset</h2>
<p>Let’s look at <a href="salmon.html">salmon.R</a>. What sort of elements are in this script?</p>
<ul>
<li>data</li>
<li>fits</li>
<li>predictions</li>
<li>plots</li>
</ul>
<p>But the elements are not like “objects”. One data set is a data frame with column headings year, wild, flow, temp and the other is a matrix with years as column headings. The fits are all different types and some have no info about what years or data I fit to (see e.g. <code>fit3</code>). The plots have to be tweaked based on the data and the fits.</p>
<p>Instead we would like to work with “objects” that have a consistent format and have all the information needed for functions that use those objects.</p>
<p><img src="images/code-org.png" width="500" /></p>
</div>
<div id="an-object" class="section level2">
<h2>An object</h2>
<ul>
<li><strong>Has a standardized form</strong> (you can describe what elements it needs to have)</li>
<li>Has all the information that subsequent functions might need to use this object.</li>
<li>Has information so you know how this object was made</li>
</ul>
</div>
<div id="how-on-earth-is-one-supposed-to-do-this" class="section level2">
<h2>How on earth is one supposed to do this?</h2>
<p><em>…if it is even worthwhile, which I’m not so sure about…</em></p>
<p>This is part of code organization. Time put into planning and standardizing your code will make you much more efficient (even if it takes time in the beginning) and will definitely help prevent errors and bugs in your code. A big coding project requires this way of thinking.</p>
</div>
<div id="how-do-get-started" class="section level2">
<h2>How do get started</h2>
<div id="do-a-little-planning-on-a-piece-of-paper.-example-data" class="section level3">
<h3>1. Do a little planning on a piece of paper. Example, <strong>data</strong>:</h3>
<div class="figure">
<img src="images/data-planning.jpg" alt="" />
<p class="caption">data planning</p>
</div>
</div>
<div id="then-start-putting-your-script-in-to-categories-data-fitting-plotting.-look-at-salmon.r" class="section level3">
<h3>2. Then start putting your script in to categories (data, fitting, plotting). Look at <a href="salmon.html">salmon.R</a></h3>
</div>
<div id="write-functions-instead-of-long-scripts." class="section level3">
<h3>3. Write functions instead of long scripts.</h3>
<p>Like <code>read_data()</code>, <code>fit_model()</code>, <code>plot1()</code>. This will naturally lead you towards “object-oriented” thinking.</p>
<p>You do not want to be duplicating your code, e.g. lines of code that fit a model or plot, over and over. You’ll just introduce impossible to find errors when you decide to change how you are fitting the data.</p>
<p>Using a few standardized (say plotting) functions will force you to move towards “object-oriented” thinking. So as opposed to copying lines of plotting code over and over when you need a plot like that.</p>
<p>For example, a script:</p>
<pre class="r"><code>par(mfrow=c(1,2))
a <- data.frame(year=2000:2009, x=1:10)
plot(a$year, a$x, xlab="year", ylab="count", ylim=c(0,100), xlim=c(1980,2010))
b <- data.frame(YEAR=1980:2009, count=1:30+50)
plot(b$YEAR, b$count, xlab="year", ylab="count", ylim=c(0,100), xlim=c(1980,2010))</code></pre>
<p><img src="coding_files/figure-html/unnamed-chunk-6-1.png" width="672" /></p>
<p>Versus writing a function and standardizing the data frames. This is a toy example.</p>
<pre class="r"><code>plot1 <- function(x, xlims=c(1980,2010), ylims=c(0,10)){
plot(x$year, x$x, xlab="year", ylab="count", ylim=ylims, xlim=xlims)
}
par(mfrow=c(1,2))
a <- data.frame(year=2000:2009, x=1:10)
b <- data.frame(year=1980:2009, x=1:30+50)
ylims <- c(min(a$x,b$x), max(a$x,b$x))
plot1(a, ylims=ylims)
plot1(b, ylims=ylims)</code></pre>
<p><img src="coding_files/figure-html/unnamed-chunk-7-1.png" width="672" /></p>
</div>
<div id="make-a-plan-for-your-functions" class="section level3">
<h3>4. Make a plan for your functions</h3>
<p>Sketch out the functions that you need to write. You’ll update this as you go along.</p>
</div>
<div id="have-your-functions-output-both-the-thing-the-info-about-that-thing" class="section level3">
<h3>5. Have your functions output both the “thing” + the info about that “thing”:</h3>
<pre><code>read_data <- function(fil, notes=NULL){
dat <- read.csv(fil)
... bunch of code to fix up the data ...
if(stringr::str_detect(fil, "Chinook")) species <- "Chinook"
if(stringr::str_detect(fil, "Coho")) species <- "Coho"
meta=list(
file=fil,
call=deparse( sys.call() ),
date=Sys.time(),
notes=notes,
species=species,
min.year=min(dat$year),
max.year=max(dat$year) )
obj <- list(meta=meta, data=dat)
return(obj)
}</code></pre>
<p>Next step for object-oriented programming: Weeks 4 and 5 will go into how to assemble your code into an R package and I’ll talk about creating formal objects and methods (like print, plot) for those objects.</p>
</div>
</div>
</div>
<div id="namespaces" class="section level1">
<h1>Namespaces</h1>
<ul>
<li>Namespaces. Every function in R belongs to a package. You can be 100% explicit in your function calls by using <code>::</code>. So <code>forecast::forecast()</code> would specify the <code>forecast</code> function in the <strong>forecast</strong> package.</li>
</ul>
<p>Why use this?</p>
<ol style="list-style-type: decimal">
<li><strong>Show in your code what package the function comes from</strong></li>
</ol>
<p>If you are reading someone else’s code, a great deal of time is lost by not knowing what package a function is from. Where is <code>dismo()</code> from?? If you write <code>dismo::dismo()</code> it is clear it is from the <strong>dismo</strong> package.</p>
<ol start="2" style="list-style-type: decimal">
<li><p>You won’t run into the problem where code fails because you forgot to do <code>library(package)</code> or <code>require(package)</code>.</p></li>
<li><p>You won’t run into problem where you have functions with the same name in two different packages or you accidentally give your function the same name as the function in a package that you need.</p></li>
</ol>
<p>This can cause disastrous things to happen to your code when you don’t use Namespaces. Let’s say, unbeknownst to you, someone using your code defines a function called <code>auto.arima()</code>.</p>
<pre class="r"><code>auto.arima <- function(x){x}</code></pre>
<p>Then in your code, you call the <code>auto.arima()</code> function in the <strong>forecast</strong> package. Because <code>auto.arima()</code> exists in the user’s working directory (global environment), your code fails. <code>auto.arima()</code> should fit a model but it doesn’t since it is overwritten by the user’s function.</p>
<pre class="r"><code>library(forecast)</code></pre>
<pre><code>## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo</code></pre>
<pre><code>##
## Attaching package: 'forecast'</code></pre>
<pre><code>## The following object is masked _by_ '.GlobalEnv':
##
## auto.arima</code></pre>
<pre class="r"><code>auto.arima(1:10)</code></pre>
<pre><code>## [1] 1 2 3 4 5 6 7 8 9 10</code></pre>
<p>We have to remove the user’s <code>auto.arima()</code> to get <strong>forecast</strong>’s function.</p>
<pre class="r"><code>rm(auto.arima)
auto.arima(1:10)</code></pre>
<pre><code>## Series: 1:10
## ARIMA(0,1,0) with drift
##
## Coefficients:
## drift
## 1
##
## sigma^2 estimated as 0: log likelihood=Inf
## AIC=-Inf AICc=-Inf BIC=-Inf</code></pre>
<p>If we use <code>forecast::auto.arima()</code>, we never run into that problem.</p>
<p>While this may seem rare, when it does happen, it makes a bug that is very hard to track down. Note, for writing packages, use of <code>::</code> is required.</p>
</div>
<div id="various-tips-and-quirks-of-r" class="section level1">
<h1>Various Tips and Quirks of R</h1>
<ul>
<li>Do not hard code any variables into your scripts or code. Ok. The reality is, you will. Try to hard code <strong>less</strong>. The more you avoid hard-coding, the faster you will be.</li>
</ul>
<p>So not this</p>
<pre class="r"><code>x <- 1
for(i in 1:10) x <- c(x, 2*i)</code></pre>
<p>but this</p>
<pre class="r"><code>n <- 10
w <- 2
x <- 1
for(i in 1:n) x <- c(x, w*i)</code></pre>
<ul>
<li>Your working directory environment is your enemy (for bugs at least). You will have to keep it clean <code>rm(list=ls())</code>, use Rmarkdown files to run code (because that uses a clean environment), or assemble your code into an R package.</li>
</ul>
<p>You can use caching in Rmarkdown files for long runs or save simulation output to Rdata files using <code>save()</code>.</p>
<p><em>All R coders forget this periodically and have wasted significant hours debugging due to a variable left in their environment.</em></p>
<ul>
<li>Use <code>class()</code> to figure out what R thinks an objects class is. The class of an object determines many things about how R functions respond to an object.</li>
</ul>
<p>For data.frames, you can use the following code to find out the class of all columns:</p>
<pre class="r"><code>a <- data.frame(l = letters, n=1:26)
unlist(lapply(a, class))</code></pre>
<pre><code>## l n
## "factor" "integer"</code></pre>
<p>Note this does not work because <code>apply</code> is for matrices not data frames.</p>
<pre class="r"><code>apply(df, 2, class)</code></pre>
<pre><code>## Error in apply(df, 2, class): dim(X) must have a positive length</code></pre>
<ul>
<li>Data frames are lists not matrices.</li>
</ul>
<p>Sadly R does not tell you this. And you’ll get errors that can be hard to decipher.</p>
<pre class="r"><code>a <- data.frame(a=1:10, b=1:10, c=1:10)
a[,1:2]%*%t(a[,1:2])</code></pre>
<pre><code>## Error in a[, 1:2] %*% t(a[, 1:2]): requires numeric/complex matrix/vector arguments</code></pre>
<p>The code above doesn’t work because <code>a</code> is not a matrix no matter how much it looks and acts like one.</p>
<pre class="r"><code>class(a[,1:2]) # data.frame
class(t(a[,1:2])) # matrix ??
class(a[[1]]) # integer
class(a[1]) # data.frame
class(unlist(a)) # integer</code></pre>
<ul>
<li>Factors (in data frames) is cause of much trouble. You can avoid with <code>stringsAsFactors=FALSE</code></li>
</ul>
<pre class="r"><code>a <- data.frame(a=letters, b=1:26, stringsAsFactors=FALSE)
unlist(lapply(a,class))</code></pre>
<pre><code>## a b
## "character" "integer"</code></pre>
<p>Figuring out when you need a character to be a “factor” and when you need it to be a “character” will lead to much suffering, but with time, you’ll figure it out. Remember, <code>class()</code> is your friend.</p>
<ul>
<li>R “helps” you bu changing class on your objects…<strong>silently</strong>. This will cause a frightful number of mysterious bugs and errors.</li>
</ul>
<p>Example:</p>
<pre class="r"><code>a <- data.frame(a=1:10, b=letters[1:10], stringsAsFactors=FALSE)
apply(a, 2, function(x){x[1:2]})</code></pre>
<pre><code>## a b
## [1,] " 1" "a"
## [2,] " 2" "b"</code></pre>
<p>What just happened? Why is the <code>a</code> column a character now? <code>apply</code> needs a matrix, so R <em>silently</em> turned your data frame into a matrix. In a matrix all elements need to be the same class. So in this case, R <em>silently</em> changed your numbers to characters. This behavior will also cause mysterious bugs.</p>
<p>Here’s another example. R changes an object of class <code>matrix</code> to class <code>vector</code>.</p>
<pre class="r"><code>a <- matrix(1, 3, 3)
apply(a, 2, mean) # this works
apply(a[,1:2], 2, mean) # this works
apply(a[,1], 2, mean) # this throws an error???</code></pre>
<pre><code>## Error in apply(a[, 1], 2, mean): dim(X) must have a positive length</code></pre>
<p>What’s happening is that R dropped the dimensions when you took only one column of <code>a</code> and created a vector. <code>apply</code> will not work on a vector; it is for matrices (or arrays). You can use <code>drop=FALSE</code> to keep the dimensions.</p>
<pre class="r"><code>class(a) # matrix
class(a[,1]) #vector
class(a[,1,drop=FALSE]) #matrix</code></pre>
<ul>
<li>Use <code>FALSE</code> and <code>TRUE</code> instead of <code>F</code> and <code>T</code></li>
</ul>
<p><code>T</code> is a shortcut for <code>TRUE</code> but <code>T</code> is a very commonly used variable name (for time). <code>T</code> is not a protected name but <code>TRUE</code> is. If you use <code>T</code> as a variable name, all your code using <code>T</code> for <code>TRUE</code> will fail.</p>
<pre class="r"><code>T=10
T==TRUE</code></pre>
<pre><code>## [1] FALSE</code></pre>
<pre class="r"><code>rm(T)</code></pre>
<ul>
<li>You can overwrite most any function in R even something like <code>plot()</code>!!</li>
</ul>
<p>Say a user writes this function:</p>
<pre class="r"><code>plot <- function(x){cat("Yelp!")}</code></pre>
<p>Now this <code>plot()</code> function will make all your code with <code>plot()</code> fail. This no longer plots:</p>
<pre class="r"><code>plot(1:10)</code></pre>
<pre><code>## Yelp!</code></pre>
<p>We have to use <code>::</code> to overcome this:</p>
<pre class="r"><code>graphics::plot(1:10)</code></pre>
<p><img src="coding_files/figure-html/unnamed-chunk-25-1.png" width="672" /></p>
<p>I’ll remove <code>plot</code>.</p>
<pre class="r"><code>rm(plot)</code></pre>
<p>While this may seem like it would never happen, it definitely can happen when you share code with other people or use someone else’s code. You can waste hours trying to track down why your code is not working anymore. Use of <code>::</code>, keeping a clean working environment, use of Rmarkdown files, and use of R packages (that you write) will help protect against this problem.</p>
<ul>
<li>Don’t be afraid of using <code>for</code> loops to <em>get the job done</em>.</li>
</ul>
<p>You could spend 2-3 hours figuring out how to use <code>tapply()</code> or <strong>dplyr</strong> to do a task, or just use a <code>for</code> loop.</p>
<ul>
<li><a href="https://r4ds.had.co.nz/pipes.html">Piping</a> means compact code, less memory consumption…. and can be terribly slow computationally. Avoid in simulations.</li>
</ul>
<p>What’s piping? It’s a function <code>%>%</code> in the <strong>magrittr</strong> that allows you to string operations together.</p>
<pre class="r"><code>library(magrittr)
rnorm(100) %>%
matrix(ncol = 2) %>%
apply(2,mean)</code></pre>
<pre><code>## [1] 0.04532255 0.13037474</code></pre>
<ul>
<li>Gravitate towards a standard coding style.</li>
</ul>
<p>Don’t make one up. Use a standard one. I use mainly the <a href="https://style.tidyverse.org/">tidyverse style guide</a> (or I try). There is a package called <strong>styler</strong> that has a RStudio plugin that makes it super easy to restyle all your code.</p>
<ul>
<li>Gravitate towards a standardized data format.</li>
</ul>
<p>It’s easier to reuse your plotting functions (and others) if you do that. I use a format similar to <a href="https://r4ds.had.co.nz/tidy-data.html">tidy data</a>. Try to use the same column headings across projects. Using <code>Brood_Year</code>, <code>year</code>, <code>BROOD_YEAR</code>, and <code>brood.year</code> for brood year across data projects, really slows you down. I see this all the time (and have to fight my own tendency to do this).</p>
<ul>
<li>Gravitate towards a standardized names for things you use in your code consistently.</li>
</ul>
<p>Using <code>alpha</code>, <code>alp</code>, <code>Alpha</code>, <code>a</code> for the same thing in different coding projects makes re-using code much slower.</p>
<ul>
<li>Use the <strong>here</strong> package along with <code>file.path()</code> to avoid hard-wired directory names.</li>
</ul>
<p>This will properly construct file paths for whatever operating system you are on. Use the RStudio project feature to get you to the right working directory (that means make sure your project is showing in the top right corner in RStudio).</p>
<p>Instead of this:</p>
<pre><code>setwd('~/GitHub/RWorkflow-NWFSC-2020/data/salmon.R')</code></pre>
<p>Use:</p>
<pre><code>fil <- file.path(here::here(), "data", "salmon.R")
fil</code></pre>
<p>That way when you share your code or switch computers, the code doesn’t break.</p>
</div>
<div id="week-3" class="section level1">
<h1>Week 3</h1>
<p>Brief summary of some debugging tools in R and RStudio + mostly RMarkdown.</p>
<ul>
<li>debugging functions</li>
<li>bench-marking</li>
<li>profiling</li>
</ul>
</div>
<hr>
<div style="text-align: center">
<i class="fas fa-cubes"></i> NWFSC Math Bio Program <i class="fas fa-cubes"></i>
</div>
</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>
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
$(document).ready(function () {
$('.tabset-dropdown > .nav-tabs > li').click(function () {
$(this).parent().toggleClass('nav-tabs-open')
});
});
</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",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_');
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = false;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>