forked from cis-ds/course-site
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock012_debugging.html
More file actions
1490 lines (1365 loc) · 480 KB
/
block012_debugging.html
File metadata and controls
1490 lines (1365 loc) · 480 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
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 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>Debugging and defensive programming</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>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-45631879-2', 'auto');
ga('send', 'pageview');
</script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<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: 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;
}
</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">Computing for the Social Sciences</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="faq.html">FAQ</a>
</li>
<li>
<a href="syllabus.html">Syllabus</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Debugging and defensive programming</h1>
</div>
<div id="objectives" class="section level1">
<h1>Objectives</h1>
<ul>
<li>Define a bug</li>
<li>Review best practices for reading, writing, and styling code</li>
<li>Distinguish between errors, warnings, and messages</li>
<li>Introduce <code>traceback()</code> and explain how to read it</li>
<li>Identify and practice methods for error handling and recovery</li>
</ul>
<div id="prerequisites" class="section level2">
<h2>Prerequisites</h2>
<ul>
<li><a href="http://adv-r.had.co.nz/Exceptions-Debugging.html">Debugging, condition handling, and defensive programming in <em>Advanced R</em> by Hadley Wickham</a></li>
<li><a href="http://r4ds.had.co.nz/iteration.html#dealing-with-failure">21.6 Dealing with failure in <em>R for Data Science</em></a></li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(tidyverse)
<span class="kw">set.seed</span>(<span class="dv">1234</span>)</code></pre></div>
</div>
</div>
<div id="bugs" class="section level1">
<h1>Bugs</h1>
<div class="figure">
<img src="images/bugs.jpg" alt="Not the kind of bugs we’re looking for" />
<p class="caption">Not the kind of bugs we’re looking for</p>
</div>
<p>A <strong>software bug</strong> is “an error, flaw, failure or fault in a computer program or system that causes it to produce an incorrect or unexpected result, or to behave in unintended ways.”<a href="#fn1" class="footnoteRef" id="fnref1"><sup>1</sup></a> In an ideal world, the computer will warn you when it encounters a bug. R has the ability to do this in some situations (see our discussion below of errors, warnings, and messages). However bugs also arise because you expect it to do one thing but provide it the ability to perform different from expectations. As I have repeatedly emphasized in class, <strong>computers are powerful tools that are incredibly stupid</strong>. They will do exactly what you tell them to, nothing more and nothing less. If you write your code in a way that allows it to behave in an unintended way, this is your fault. The first goal of debugging should be to prevent unintended behaviors before they strike. However, when such bugs occur we need the tools and knowledge to track down these unintended behaviors and correct them in our code.</p>
</div>
<div id="defensive-programming" class="section level1">
<h1>Defensive programming</h1>
<p>The most important step to debugging is to prevent bugs in the first place. There are several methods we can employ to do that. Some of them are simple such as styling our code so that we follow consistent practices when writing scripts and programs. Consistency will prevent silly and minor mistakes such as typos. Good styles also make our code more <strong>readable</strong> for the human eye and allow us to isolate and detect errors merely by looking at the screen. Others are more advanced and focus on the concept of <strong>failing fast</strong> - as soon as something goes wrong, stop executing the program and announce an error.</p>
<div id="writing-code" class="section level2">
<h2>Writing code</h2>
<p>Think back to <a href="http://cfss.uchicago.edu/setup00.html#introduction">the analogy of programming languages to human languages</a>. Programming languages adhere to a specific grammar and syntax, they contain a vocabulary, etymology, cultural conventions, word roots (prefixes and suffixes), just like English or any other written or spoken language. We can therefore equate different components of a program to their language counterparts:</p>
<table>
<thead>
<tr class="header">
<th>Programming</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Scripts</td>
<td>Essays</td>
</tr>
<tr class="even">
<td>Sections</td>
<td>Paragraphs</td>
</tr>
<tr class="odd">
<td>Lines Breaks</td>
<td>Sentences</td>
</tr>
<tr class="even">
<td>Parentheses</td>
<td>Punctuation</td>
</tr>
<tr class="odd">
<td>Functions</td>
<td>Verbs</td>
</tr>
<tr class="even">
<td>Variables</td>
<td>Nouns</td>
</tr>
</tbody>
</table>
<p>Now think about how you write a document in English. The United States just recently commemorated the 30th anniversary of <a href="https://en.wikipedia.org/wiki/Space_Shuttle_Challenger_disaster">the explosion of the Challenger space shuttle</a>, when seven crew members were tragically killed just 73 seconds after takeoff. Their deaths were seen live by millions of American schoolchildren watching around the country. A few hours after the tragedy, President Ronald Reagan gave a national address. Here is an excerpt of that address:</p>
<blockquote>
<p>weve grown used to wonders in this century its hard to dazzle us but for 25 years the united states space program has been doing just that weve grown used to the idea of space and perhaps we forget that weve only just begun were still pioneers they the members of the Challenger crew were pioneers and i want to say something to the school children of America who were watching the live coverage of the shuttles takeoff i know it is hard to understand but sometimes painful things like this happen its all part of the process of exploration and discovery its all part of taking a chance and expanding mans horizons the future doesnt belong to the fainthearted it belongs to the brave the challenger crew was pulling us into the future and well continue to follow them the crew of the space shuttle challenger honored us by the manner in which they lived their lives we will never forget them nor the last time we saw them this morning as they prepared for the journey and waved goodbye and slipped the surly bonds of earth to touch the face of god</p>
</blockquote>
<p>Wait a minute, this doesn’t look right. What happened to the punctuation? The capitalization? Where are all the sentences and paragraph breaks? Isn’t this hard to read and understand? Do you feel any of the emotions of the moment? Probably not, because the normal rules of grammar and syntax have been destroyed. Here’s the same excerpt, but properly styled:</p>
<blockquote>
<p>We’ve grown used to wonders in this century. It’s hard to dazzle us. But for 25 years the United States space program has been doing just that. We’ve grown used to the idea of space, and perhaps we forget that we’ve only just begun. We’re still pioneers. They, the members of the Challenger crew, were pioneers.</p>
</blockquote>
<blockquote>
<p>And I want to say something to the school children of America who were watching the live coverage of the shuttle’s takeoff. I know it is hard to understand, but sometimes painful things like this happen. It’s all part of the process of exploration and discovery. It’s all part of taking a chance and expanding man’s horizons. The future doesn’t belong to the fainthearted; it belongs to the brave. The Challenger crew was pulling us into the future, and we’ll continue to follow them….</p>
</blockquote>
<blockquote>
<p>The crew of the space shuttle Challenger honoured us by the manner in which they lived their lives. We will never forget them, nor the last time we saw them, this morning, as they prepared for the journey and waved goodbye and ‘slipped the surly bonds of earth’ to ‘touch the face of God.’</p>
</blockquote>
<p>That makes much more sense. Adhering to standard rules of style make the text more legible and interpretable. This is what we should aim for when writing programs in R.<a href="#fn2" class="footnoteRef" id="fnref2"><sup>2</sup></a></p>
</div>
<div id="style-guide" class="section level2">
<h2>Style guide</h2>
<p>Here are some common rules you should adopt when writing code in R, adapted from Hadley Wickham’s <a href="http://adv-r.had.co.nz/Style.html">style guide</a>.</p>
<div id="notation-and-naming" class="section level3">
<h3>Notation and naming</h3>
<div id="file-names" class="section level4">
<h4>File names</h4>
<p>Files should have intuitive and meaningful names. Avoid spaces or non-standard characters in your file names. R scripts should always end in <code>.R</code>; R Markdown documents should always end in <code>.Rmd</code>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Good</span>
fit-models.R
utility-functions.R
gun-deaths.Rmd
<span class="co"># Bad</span>
foo.r
stuff.r
gun deaths.rmd</code></pre></div>
</div>
<div id="object-names" class="section level4">
<h4>Object names</h4>
<p>Variables refer to data objects such as vectors, lists, or data frames. Variable and function names should be lowercase. Use an underscore (<code>_</code>) to separate words within a name. Avoid using periods (<code>.</code>). Variable names should generally be nouns and function names should be verbs. Try to pick names that are concise and meaningful.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Good</span>
day_one
day_1
<span class="co"># Bad</span>
first_day_of_the_month
DayOne
dayone
djm1</code></pre></div>
<p>Where possible, avoid using names of existing functions and variables. Doing so will cause confusion for the readers of your code, not to mention make it difficult to access the existing functions and variables.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Bad</span>
T <-<span class="st"> </span><span class="ot">FALSE</span>
c <-<span class="st"> </span><span class="dv">10</span></code></pre></div>
<p>For instance, what would happen if I created a new <code>mean()</code> function?</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">x <-<span class="st"> </span><span class="dv">1</span>:<span class="dv">10</span>
<span class="kw">mean</span>(x)</code></pre></div>
<pre><code>## [1] 5.5</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># create new mean function</span>
mean <-<span class="st"> </span>function(x) <span class="kw">sum</span>(x)
<span class="kw">mean</span>(x)</code></pre></div>
<pre><code>[1] 55</code></pre>
<div class="figure">
<img src="http://i.giphy.com/BxWTWalKTUAdq.gif" />
</div>
</div>
</div>
<div id="syntax" class="section level3">
<h3>Syntax</h3>
<div id="spacing" class="section level4">
<h4>Spacing</h4>
<p>Place spaces around all <a href="https://www.programiz.com/r-programming/infix-operator">infix</a> operators (=, +, -, <-, etc.). The same rule applies when using <code>=</code> in function calls.</p>
<blockquote>
<p>Always put a space after a comma, and never before (just like in regular English).</p>
</blockquote>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Good</span>
average <-<span class="st"> </span><span class="kw">mean</span>(feet /<span class="st"> </span><span class="dv">12</span> +<span class="st"> </span>inches, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)
<span class="co"># Bad</span>
average<-<span class="kw">mean</span>(feet/<span class="dv">12</span>+inches,<span class="dt">na.rm=</span><span class="ot">TRUE</span>)</code></pre></div>
<p>Place a space before left parentheses, except in a function call.</p>
<blockquote>
<p>Note: I’m terrible at remembering to do this for <code>if-else</code> or <code>for</code> loops. I typically never place a space before left parentheses, but it is supposed to be good practice. Just remember to be consistent whatever approach you choose.</p>
</blockquote>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Good</span>
if (debug) <span class="kw">do</span>(x)
<span class="kw">plot</span>(x, y)
<span class="co"># Bad</span>
if(debug)<span class="kw">do</span>(x)
<span class="kw">plot</span> (x, y)</code></pre></div>
<p>Do not place spaces around code in parentheses or square brackets (unless there’s a comma, in which case see above).</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Good</span>
if (debug) <span class="kw">do</span>(x)
diamonds[<span class="dv">5</span>, ]
<span class="co"># Bad</span>
if ( debug ) <span class="kw">do</span>(x) <span class="co"># No spaces around debug</span>
x[<span class="dv">1</span>,] <span class="co"># Needs a space after the comma</span>
x[<span class="dv">1</span> ,] <span class="co"># Space goes after comma not before</span></code></pre></div>
</div>
<div id="curly-braces" class="section level4">
<h4>Curly braces</h4>
<p>An opening curly brace should never go on its own line and should always be followed by a new line. A closing curly brace should always go on its own line, unless it’s followed by else.</p>
<p>Always indent the code inside curly braces.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Good</span>
if (y <<span class="st"> </span><span class="dv">0</span> &&<span class="st"> </span>debug) {
<span class="kw">message</span>(<span class="st">"Y is negative"</span>)
}
if (y ==<span class="st"> </span><span class="dv">0</span>) {
<span class="kw">log</span>(x)
} else {
y ^<span class="st"> </span>x
}
<span class="co"># Bad</span>
if (y <<span class="st"> </span><span class="dv">0</span> &&<span class="st"> </span>debug)
<span class="kw">message</span>(<span class="st">"Y is negative"</span>)
if (y ==<span class="st"> </span><span class="dv">0</span>) {
<span class="kw">log</span>(x)
}
else {
y ^<span class="st"> </span>x
}</code></pre></div>
<p>It’s ok to leave very short statements on the same line:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">if (y <<span class="st"> </span><span class="dv">0</span> &&<span class="st"> </span>debug) <span class="kw">message</span>(<span class="st">"Y is negative"</span>)</code></pre></div>
</div>
<div id="line-length" class="section level4">
<h4>Line length</h4>
<p>Strive to limit your code to 80 characters per line. This fits comfortably on a printed page with a reasonably sized font. For instance, if I wanted to convert the <code>chief</code> column to an <a href="http://r4ds.had.co.nz/factors.html">ordered factor</a> for building a <a href="https://github.com/uc-cfss/hw03/blob/master/demo/scotus_solution.md#solution-using-facets-and-showing-whole-data-on-each-facet-getting-harder">faceted graph</a>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Good</span>
scdbv <-<span class="st"> </span><span class="kw">mutate</span>(scdbv,
<span class="dt">chief =</span> <span class="kw">factor</span>(chief, <span class="dt">levels =</span> <span class="kw">c</span>(<span class="st">"Jay"</span>, <span class="st">"Rutledge"</span>, <span class="st">"Ellsworth"</span>,
<span class="st">"Marshall"</span>, <span class="st">"Taney"</span>, <span class="st">"Chase"</span>,
<span class="st">"Waite"</span>, <span class="st">"Fuller"</span>, <span class="st">"White"</span>,
<span class="st">"Taft"</span>, <span class="st">"Hughes"</span>, <span class="st">"Stone"</span>,
<span class="st">"Vinson"</span>, <span class="st">"Warren"</span>, <span class="st">"Burger"</span>,
<span class="st">"Rehnquist"</span>, <span class="st">"Roberts"</span>)))
<span class="co"># Bad</span>
scdbv <-<span class="st"> </span><span class="kw">mutate</span>(scdbv, <span class="dt">chief =</span> <span class="kw">factor</span>(chief, <span class="dt">levels =</span> <span class="kw">c</span>(<span class="st">"Jay"</span>, <span class="st">"Rutledge"</span>, <span class="st">"Ellsworth"</span>, <span class="st">"Marshall"</span>, <span class="st">"Taney"</span>, <span class="st">"Chase"</span>, <span class="st">"Waite"</span>, <span class="st">"Fuller"</span>, <span class="st">"White"</span>, <span class="st">"Taft"</span>, <span class="st">"Hughes"</span>, <span class="st">"Stone"</span>, <span class="st">"Vinson"</span>, <span class="st">"Warren"</span>, <span class="st">"Burger"</span>, <span class="st">"Rehnquist"</span>, <span class="st">"Roberts"</span>)))</code></pre></div>
</div>
<div id="indentation" class="section level4">
<h4>Indentation</h4>
<p>When indenting your code, use two spaces. Never use tabs or mix tabs and spaces.</p>
<blockquote>
<p>By default, RStudio automatically converts tabs to two spaces in your code. So if you use the tab button in R Studio, you’re good to go.</p>
</blockquote>
<div class="figure">
<img src="images/tab_indent.png" alt="Insert spaces for tab setting in RStudio" />
<p class="caption">“Insert spaces for tab” setting in RStudio</p>
</div>
<p>The only exception is if a function definition runs over multiple lines. In that case, indent the second line to where the definition starts:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># pure function</span>
long_function_name <-<span class="st"> </span>function(<span class="dt">a =</span> <span class="st">"a long argument"</span>,
<span class="dt">b =</span> <span class="st">"another argument"</span>,
<span class="dt">c =</span> <span class="st">"another long argument"</span>) {
<span class="co"># As usual code is indented by two spaces.</span>
}
<span class="co"># in a mutate() function</span>
scdbv <-<span class="st"> </span>scdbv %>%
<span class="st"> </span><span class="kw">mutate</span>(<span class="dt">majority =</span> majority -<span class="st"> </span><span class="dv">1</span>,
<span class="dt">chief =</span> <span class="kw">factor</span>(chief, <span class="dt">levels =</span> <span class="kw">c</span>(<span class="st">"Jay"</span>, <span class="st">"Rutledge"</span>, <span class="st">"Ellsworth"</span>,
<span class="st">"Marshall"</span>, <span class="st">"Taney"</span>, <span class="st">"Chase"</span>,
<span class="st">"Waite"</span>, <span class="st">"Fuller"</span>, <span class="st">"White"</span>,
<span class="st">"Taft"</span>, <span class="st">"Hughes"</span>, <span class="st">"Stone"</span>,
<span class="st">"Vinson"</span>, <span class="st">"Warren"</span>, <span class="st">"Burger"</span>,
<span class="st">"Rehnquist"</span>, <span class="st">"Roberts"</span>)))</code></pre></div>
</div>
<div id="assignment" class="section level4">
<h4>Assignment</h4>
<p>Use <code><-</code>, not <code>=</code>, for assignment. Why? Because I said so. <a href="http://stackoverflow.com/a/1742550">Or read more here</a>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Good</span>
x <-<span class="st"> </span><span class="dv">5</span>
<span class="co"># Bad</span>
x =<span class="st"> </span><span class="dv">5</span></code></pre></div>
</div>
</div>
<div id="comments" class="section level3">
<h3>Comments</h3>
<p>Comment your code. Each line of a comment should begin with the comment symbol and a single space: <code>#</code>. Comments should explain the why, not the what.</p>
<p>To take advantage of RStudio’s <a href="https://support.rstudio.com/hc/en-us/articles/200484568-Code-Folding-and-Sections">code folding feature</a>, add at least four trailing dashes (-), equal signs (=), or pound signs (#) after the comment text</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Section One ---------------------------------</span>
<span class="co"># Section Two =================================</span>
### Section Three #############################</code></pre></div>
</div>
</div>
<div id="auto-formatting-in-rstudio" class="section level2">
<h2>Auto-formatting in RStudio</h2>
<p>There are two built-in methods of using RStudio to automatically format and clean up your code. They are not perfect, but can help in some circumstances.</p>
<div id="format-code" class="section level3">
<h3>Format code</h3>
<p><strong>Code > Reformat Code</strong> (Shift + Cmd/Ctrl + A)</p>
<div id="bad-code" class="section level5">
<h5>Bad code</h5>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># comments are retained</span>
<span class="dv">1+1</span>
if(<span class="ot">TRUE</span>){
x=<span class="dv">1</span> <span class="co"># inline comments</span>
}else{
x=<span class="dv">2</span>;<span class="kw">print</span>(<span class="st">'Oh no... ask the right bracket to go away!'</span>)}
<span class="dv">1</span>*<span class="dv">3</span> <span class="co"># one space before this comment will become two!</span>
<span class="dv">2+2+2</span> <span class="co"># only 'single quotes' are allowed in comments</span>
diamonds %>%
<span class="kw">filter</span>(color ==<span class="st"> "I"</span>) %>%
<span class="kw">group_by</span>(cut) %>%
<span class="kw">summarize</span>(<span class="dt">price =</span> <span class="kw">mean</span>(price))
<span class="kw">lm</span>(y~x1+x2, <span class="dt">data=</span><span class="kw">data.frame</span>(<span class="dt">y=</span><span class="kw">rnorm</span>(<span class="dv">100</span>),<span class="dt">x1=</span><span class="kw">rnorm</span>(<span class="dv">100</span>),<span class="dt">x2=</span><span class="kw">rnorm</span>(<span class="dv">100</span>))) ### a linear model
<span class="dv">1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1</span> ## comments after a long line
## here is a long long long long long long long long long long long long long long long long long long long comment</code></pre></div>
</div>
<div id="better-code" class="section level5">
<h5>Better code</h5>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># comments are retained</span>
<span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span>
if (<span class="ot">TRUE</span>) {
x =<span class="st"> </span><span class="dv">1</span> <span class="co"># inline comments</span>
} else{
x =<span class="st"> </span><span class="dv">2</span>
<span class="kw">print</span>(<span class="st">'Oh no... ask the right bracket to go away!'</span>)
}
<span class="dv">1</span> *<span class="st"> </span><span class="dv">3</span> <span class="co"># one space before this comment will become two!</span>
<span class="dv">2</span> +<span class="st"> </span><span class="dv">2</span> +<span class="st"> </span><span class="dv">2</span> <span class="co"># only 'single quotes' are allowed in comments</span>
diamonds %>%
<span class="kw">filter</span>(color ==<span class="st"> "I"</span>) %>%
<span class="kw">group_by</span>(cut) %>%
<span class="kw">summarize</span>(<span class="dt">price =</span> <span class="kw">mean</span>(price))
<span class="kw">lm</span>(y ~<span class="st"> </span>x1 +<span class="st"> </span>x2, <span class="dt">data =</span> <span class="kw">data.frame</span>(
<span class="dt">y =</span> <span class="kw">rnorm</span>(<span class="dv">100</span>),
<span class="dt">x1 =</span> <span class="kw">rnorm</span>(<span class="dv">100</span>),
<span class="dt">x2 =</span> <span class="kw">rnorm</span>(<span class="dv">100</span>)
)) ### a linear model
<span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +
<span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> ## comments after a long line
## here is a long long long long long long long long long long long long long long long long long long long comment</code></pre></div>
<p><strong>Format code</strong> will attempt to adjust the source code formatting to adhere to the style guide specified above. It doesn’t look perfect, but is more readable than the original. We should still clean up some of this manually, such as the comment on the last line that flows over.</p>
</div>
</div>
<div id="reindent-lines" class="section level3">
<h3>Reindent lines</h3>
<p><strong>Code > Reindent Lines</strong> (Cmd/Ctrl + I)</p>
<div id="bad-code-1" class="section level5">
<h5>Bad code</h5>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># comments are retained</span>
<span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span>
if (<span class="ot">TRUE</span>) {
x =<span class="st"> </span><span class="dv">1</span> <span class="co"># inline comments</span>
} else{
x =<span class="st"> </span><span class="dv">2</span>
<span class="kw">print</span>(<span class="st">'Oh no... ask the right bracket to go away!'</span>)
}
<span class="dv">1</span> *<span class="st"> </span><span class="dv">3</span> <span class="co"># one space before this comment will become two!</span>
<span class="dv">2</span> +<span class="st"> </span><span class="dv">2</span> +<span class="st"> </span><span class="dv">2</span> <span class="co"># only 'single quotes' are allowed in comments</span>
diamonds %>%
<span class="kw">filter</span>(color ==<span class="st"> "I"</span>) %>%
<span class="kw">group_by</span>(cut) %>%
<span class="kw">summarize</span>(<span class="dt">price =</span> <span class="kw">mean</span>(price))
<span class="kw">lm</span>(y ~<span class="st"> </span>x1 +<span class="st"> </span>x2, <span class="dt">data =</span> <span class="kw">data.frame</span>(
<span class="dt">y =</span> <span class="kw">rnorm</span>(<span class="dv">100</span>),
<span class="dt">x1 =</span> <span class="kw">rnorm</span>(<span class="dv">100</span>),
<span class="dt">x2 =</span> <span class="kw">rnorm</span>(<span class="dv">100</span>)
)) ### a linear model
<span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +
<span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> ## comments after a long line
## here is a long long long long long long long long long long long long long long long long long long long comment</code></pre></div>
</div>
<div id="better-code-1" class="section level5">
<h5>Better code</h5>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># comments are retained</span>
<span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span>
if (<span class="ot">TRUE</span>) {
x =<span class="st"> </span><span class="dv">1</span> <span class="co"># inline comments</span>
} else{
x =<span class="st"> </span><span class="dv">2</span>
<span class="kw">print</span>(<span class="st">'Oh no... ask the right bracket to go away!'</span>)
}
<span class="dv">1</span> *<span class="st"> </span><span class="dv">3</span> <span class="co"># one space before this comment will become two!</span>
<span class="dv">2</span> +<span class="st"> </span><span class="dv">2</span> +<span class="st"> </span><span class="dv">2</span> <span class="co"># only 'single quotes' are allowed in comments</span>
diamonds %>%
<span class="st"> </span><span class="kw">filter</span>(color ==<span class="st"> "I"</span>) %>%
<span class="st"> </span><span class="kw">group_by</span>(cut) %>%
<span class="st"> </span><span class="kw">summarize</span>(<span class="dt">price =</span> <span class="kw">mean</span>(price))
<span class="kw">lm</span>(y ~<span class="st"> </span>x1 +<span class="st"> </span>x2, <span class="dt">data =</span> <span class="kw">data.frame</span>(
<span class="dt">y =</span> <span class="kw">rnorm</span>(<span class="dv">100</span>),
<span class="dt">x1 =</span> <span class="kw">rnorm</span>(<span class="dv">100</span>),
<span class="dt">x2 =</span> <span class="kw">rnorm</span>(<span class="dv">100</span>)
)) ### a linear model
<span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +
<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> +<span class="st"> </span><span class="dv">1</span> ## comments after a long line
## here is a long long long long long long long long long long long long long long long long long long long comment</code></pre></div>
<p><strong>Reindent lines</strong> will add spacing to conditional expression blocks, multi-line functions, expressions which run over multiple lines, and piped operations. Again, it is not perfect but it does some of the formatting work for us.</p>
</div>
</div>
</div>
<div id="exercise-style-this-code" class="section level2">
<h2>Exercise: style this code</h2>
<p>Here’s a chunk of code from an exercise in another class. It is formatted terribly, but as you can see it does work - the computer can interpret it. Use the style guide to clean it up and make it readable.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(tidyverse)
<span class="kw">set.seed</span>(<span class="dv">1234</span>)
<span class="co"># function to calculate growth in annual income ####</span>
annual_income<-function(base_inc,p,g,sigma,n_years,<span class="dt">start_year=</span><span class="dv">2018</span>){
errors<-<span class="kw">rnorm</span>(n_years,<span class="dt">mean=</span><span class="dv">0</span>,<span class="dt">sd=</span>sigma)
annual_income_log<-<span class="kw">vector</span>(<span class="st">"numeric"</span>,n_years)
for(year in <span class="kw">seq_len</span>(n_years)){if(year ==<span class="st"> </span><span class="dv">1</span>){annual_income_log[[year]] <-<span class="st"> </span><span class="kw">log</span>(base_inc) +<span class="st"> </span>errors[[year]]}
else{annual_income_log[[year]]<-(<span class="dv">1</span>-p)*(<span class="kw">log</span>(base_inc)+g*(year<span class="dv">-1</span>))+p*annual_income_log[[year<span class="dv">-1</span>]]+errors[[year]]}
}
<span class="kw">data_frame</span>(<span class="dt">inc=</span><span class="kw">exp</span>(annual_income_log),<span class="dt">year=</span><span class="dv">2018</span>+<span class="kw">seq_len</span>(n_years)-<span class="dv">1</span>)}
<span class="co"># part 1 - simulate 1000 times ####</span>
n_sims<-<span class="dv">1000</span>
n_years<-<span class="dv">40</span>
<span class="co"># simulate the data, then coerce into a data frame ####</span>
sim_income <-<span class="st"> </span>n_sims %>%
<span class="kw">rerun</span>(<span class="kw">annual_income</span>(<span class="dt">base_inc =</span> <span class="dv">80000</span>, <span class="dt">p =</span> .<span class="dv">2</span>,<span class="dt">g =</span> .<span class="dv">03</span>, <span class="dt">sigma =</span> .<span class="dv">1</span>,<span class="dt">n_years =</span> n_years, <span class="dt">start_year =</span> <span class="dv">2018</span>)) %>%<span class="kw">bind_rows</span>(<span class="dt">.id =</span> <span class="st">"id"</span>) %>%<span class="kw">select</span>(id, year, inc)
## plot the first income path ####
sim_income %>%<span class="kw">filter</span>(id ==<span class="st"> </span><span class="dv">1</span>) %>%
<span class="kw">ggplot</span>(<span class="kw">aes</span>(year, inc)) +
<span class="kw">geom_line</span>() +
<span class="kw">labs</span>(<span class="dt">title =</span> <span class="st">"Simulated income growth over time (one simulation)"</span>,<span class="dt">x =</span> <span class="st">"Year"</span>,<span class="dt">y =</span> <span class="st">"Annual Income"</span>) +<span class="kw">scale_y_continuous</span>(<span class="dt">labels =</span> scales::dollar)</code></pre></div>
<p><img src="block012_debugging_files/figure-html/exercise_bad-1.png" width="672" /></p>
<details> <summary>Click for the solution</summary>
<p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(tidyverse)
<span class="kw">set.seed</span>(<span class="dv">1234</span>)
<span class="co"># function to calculate growth in annual income ####</span>
annual_income <-<span class="st"> </span>function(base_inc, p, g, sigma, n_years, <span class="dt">start_year =</span> <span class="dv">2018</span>) {
errors <-<span class="st"> </span><span class="kw">rnorm</span>(n_years, <span class="dt">mean =</span> <span class="dv">0</span>, <span class="dt">sd =</span> sigma)
annual_income_log <-<span class="st"> </span><span class="kw">vector</span>(<span class="st">"numeric"</span>, n_years)
for (year in <span class="kw">seq_len</span>(n_years)) {
if (year ==<span class="st"> </span><span class="dv">1</span>) {
annual_income_log[[year]] <-<span class="st"> </span><span class="kw">log</span>(base_inc) +<span class="st"> </span>errors[[year]]
} else {
annual_income_log[[year]] <-
<span class="st"> </span>(<span class="dv">1</span> -<span class="st"> </span>p) *<span class="st"> </span>(<span class="kw">log</span>(base_inc) +<span class="st"> </span>g *<span class="st"> </span>(year -<span class="st"> </span><span class="dv">1</span>)) +
<span class="st"> </span>p *<span class="st"> </span>annual_income_log[[year -<span class="st"> </span><span class="dv">1</span>]] +<span class="st"> </span>errors[[year]]
}
}
<span class="kw">data_frame</span>(<span class="dt">inc =</span> <span class="kw">exp</span>(annual_income_log),
<span class="dt">year =</span> <span class="dv">2018</span> +<span class="st"> </span><span class="kw">seq_len</span>(n_years) -<span class="st"> </span><span class="dv">1</span>)
}
<span class="co"># part 1 - simulate 1000 times ####</span>
n_sims <-<span class="st"> </span><span class="dv">10000</span>
n_years <-<span class="st"> </span><span class="dv">40</span>
<span class="co"># simulate the data, then coerce into a data frame ####</span>
sim_income <-<span class="st"> </span>n_sims %>%
<span class="st"> </span><span class="kw">rerun</span>(
<span class="kw">annual_income</span>(
<span class="dt">base_inc =</span> <span class="dv">80000</span>,
<span class="dt">p =</span> .<span class="dv">2</span>,
<span class="dt">g =</span> .<span class="dv">03</span>,
<span class="dt">sigma =</span> .<span class="dv">1</span>,
<span class="dt">n_years =</span> n_years,
<span class="dt">start_year =</span> <span class="dv">2018</span>
)
) %>%
<span class="st"> </span><span class="kw">bind_rows</span>(<span class="dt">.id =</span> <span class="st">"id"</span>) %>%
<span class="st"> </span><span class="kw">select</span>(id, year, inc)
## plot the first income path ####
sim_income %>%
<span class="st"> </span><span class="kw">filter</span>(id ==<span class="st"> </span><span class="dv">1</span>) %>%
<span class="st"> </span><span class="kw">ggplot</span>(<span class="kw">aes</span>(year, inc)) +
<span class="st"> </span><span class="kw">geom_line</span>() +
<span class="st"> </span><span class="kw">labs</span>(<span class="dt">title =</span> <span class="st">"Simulated income growth over time (one simulation)"</span>,
<span class="dt">x =</span> <span class="st">"Year"</span>,
<span class="dt">y =</span> <span class="st">"Annual Income"</span>) +
<span class="st"> </span><span class="kw">scale_y_continuous</span>(<span class="dt">labels =</span> scales::dollar)</code></pre></div>
</p>
<p></details></p>
</div>
</div>
<div id="communicating-problems-with-conditions" class="section level1">
<h1>Communicating problems with conditions</h1>
<p><strong>Conditions</strong> are a method for communicating to the user when something unanticipated has occurred. Helpfully, many package authors will build these into their functions to explicitly communicate with users when they attempt to use the function improperly. In fact, when you write your own functions you too can use conditions to alert users when something has gone wrong. There are three levels of conditions in R, which each lead to different outcomes.</p>
<div id="types-of-conditions" class="section level2">
<h2>Types of conditions</h2>
<div id="fatal-errors" class="section level3">
<h3>Fatal errors</h3>
<p><strong>Fatal errors</strong> are raised by <code>stop()</code> and force all execution to terminate. Typically errors are used to abort code or a function when it is impossible for the function to continue.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">addition <-<span class="st"> </span>function(x, y){
if(!<span class="kw">is_numeric</span>(<span class="kw">c</span>(x, y))) <span class="kw">stop</span>(<span class="st">"One of your inputs is not a number."</span>)
x +<span class="st"> </span>y
}
<span class="kw">addition</span>(<span class="dv">3</span>, <span class="st">"abc"</span>)</code></pre></div>
<pre><code>## Error in addition(3, "abc"): One of your inputs is not a number.</code></pre>
</div>
<div id="warnings" class="section level3">
<h3>Warnings</h3>
<p><strong>Warnings</strong> are generated by <code>warning()</code> and used to display potential problems. The function or code will continue to process, but the user will be notified that something undesirable has occurred. For example, the <a href="https://en.wikipedia.org/wiki/Logit"><strong>logit</strong> transformation</a> converts a probability <span class="math inline">\(p\)</span> to the <em>log-odds</em>, or the logarithm of the odds. We can write a function to do this for us, but because probability values must be between 0 and 1, it will fail when <span class="math inline">\(x\)</span> is outside of the range <span class="math inline">\([0,1]\)</span>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">logit <-<span class="st"> </span>function(x){
<span class="kw">log</span>(x /<span class="st"> </span>(<span class="dv">1</span> -<span class="st"> </span>x))
}
<span class="kw">logit</span>(-<span class="dv">1</span>)</code></pre></div>
<pre><code>## Warning in log(x/(1 - x)): NaNs produced</code></pre>
<pre><code>## [1] NaN</code></pre>
<p>But the message produced is rather opaque. We could add a custom error message to stop the whole function:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">logit <-<span class="st"> </span>function(x){
if(x <<span class="st"> </span><span class="dv">0</span> |<span class="st"> </span>x ><span class="st"> </span><span class="dv">1</span>) <span class="kw">stop</span>(<span class="st">'x not between 0 and 1'</span>)
<span class="kw">log</span>(x /<span class="st"> </span>(<span class="dv">1</span> -<span class="st"> </span>x))
}
<span class="kw">logit</span>(-<span class="dv">1</span>)</code></pre></div>
<pre><code>## Error in logit(-1): x not between 0 and 1</code></pre>
<p>But what if instead we wanted to produce an <code>NA</code> value in these situations, and just warn the user what happened? We could revise this yet again to produce a warning message:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">logit <-<span class="st"> </span>function(x){
x <-<span class="st"> </span><span class="kw">ifelse</span>(x <<span class="st"> </span><span class="dv">0</span> |<span class="st"> </span>x ><span class="st"> </span><span class="dv">1</span>, <span class="ot">NA</span>, x)
if(<span class="kw">is.na</span>(x)) <span class="kw">warning</span>(<span class="st">'x not between 0 and 1'</span>)
<span class="kw">log</span>(x /<span class="st"> </span>(<span class="dv">1</span> -<span class="st"> </span>x))
}
<span class="kw">logit</span>(-<span class="dv">1</span>)</code></pre></div>
<pre><code>## Warning in logit(-1): x not between 0 and 1</code></pre>
<pre><code>## [1] NA</code></pre>
</div>
<div id="messages" class="section level3">
<h3>Messages</h3>
<p>Messages are generated by <code>message()</code> and are used to give informative output to the user. It doesn’t mean anything even went wrong, just that there is some information that might prove useful. You’ve seen these before in <code>ggplot()</code> when generating smoothing lines.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(diamonds, <span class="kw">aes</span>(carat, price)) +
<span class="st"> </span><span class="kw">geom_point</span>() +
<span class="st"> </span><span class="kw">geom_smooth</span>()</code></pre></div>
<pre><code>## `geom_smooth()` using method = 'gam'</code></pre>
<p><img src="block012_debugging_files/figure-html/message_ggplot-1.png" width="672" /></p>
<p>Did you see the message?</p>
<pre><code>## `geom_smooth()` using method = 'gam'</code></pre>
<p>This tells us that <code>geom_smooth()</code> generated the line using the <code>gam()</code> method.<a href="#fn3" class="footnoteRef" id="fnref3"><sup>3</sup></a> Nothing went wrong, there was no unexpected behavior, that is just the default smoothing method for a dataset of this size. But it is helpful because what if you wanted to use a linear smoothing function instead? Now you know it was not the default method, and if you want to use it you need to explicitly set it.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(diamonds, <span class="kw">aes</span>(carat, price)) +
<span class="st"> </span><span class="kw">geom_point</span>() +
<span class="st"> </span><span class="kw">geom_smooth</span>(<span class="dt">method =</span> <span class="st">"lm"</span>)</code></pre></div>
<p><img src="block012_debugging_files/figure-html/message_ggplot_override-1.png" width="672" /></p>
<p>The nice thing about messages is that they can be suppressed using the <code>suppressMessages()</code> function. This way if your function produces dozens or hundreds of messages, you can block them from being printed. A nice feature if you are knitting an R Markdown document. If you were to include messages simply by using the <code>print()</code> function, they could not be ignored.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">demo_message <-<span class="st"> </span>function() <span class="kw">message</span>(<span class="st">"This is a message"</span>)
<span class="kw">demo_message</span>()</code></pre></div>
<pre><code>## This is a message</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">suppressMessages</span>(<span class="kw">demo_message</span>()) <span class="co"># no output</span>
demo_print <-<span class="st"> </span>function() <span class="kw">print</span>(<span class="st">"This is a message"</span>)
<span class="kw">demo_print</span>()</code></pre></div>
<pre><code>## [1] "This is a message"</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">suppressMessages</span>(<span class="kw">demo_print</span>()) <span class="co"># still output</span></code></pre></div>
<pre><code>## [1] "This is a message"</code></pre>
</div>
</div>
<div id="exercise-build-a-function-with-conditions" class="section level2">
<h2>Exercise: build a function with conditions</h2>
<p>This is a basic function that calculates the square root of the sum of two numbers.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">sqrt_sum <-<span class="st"> </span>function(x, y){
<span class="kw">sqrt</span>(<span class="kw">sum</span>(x, y))
}
<span class="kw">sqrt_sum</span>(<span class="dv">3</span>, <span class="dv">6</span>)</code></pre></div>
<pre><code>## [1] 3</code></pre>
<p>However, look at what happens when the sum of the numbers is negative.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">sqrt_sum</span>(<span class="dv">3</span>, -<span class="dv">6</span>)</code></pre></div>
<pre><code>## Warning in sqrt(sum(x, y)): NaNs produced</code></pre>
<pre><code>## [1] NaN</code></pre>
<p>We get a cryptic error message. What happened? <strong>You cannot take the square root of a negative number.</strong> Let’s rewrite the function to be explicit with this.</p>
<ol style="list-style-type: decimal">
<li><p>Rewrite <code>sqrt_sum()</code> to produce a fatal error any time the sum of the two numbers is negative.</p>
<details> <summary>Click for the solution</summary>
<p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">sqrt_sum <-<span class="st"> </span>function(x, y){
if(<span class="kw">sum</span>(x, y) <<span class="st"> </span><span class="dv">0</span>) <span class="kw">stop</span>(<span class="st">"The sum of these numbers is negative."</span>)
<span class="kw">sqrt</span>(x +<span class="st"> </span>y)
}
<span class="kw">sqrt_sum</span>(<span class="dv">3</span>, -<span class="dv">6</span>)</code></pre></div>
<pre><code>## Error in sqrt_sum(3, -6): The sum of these numbers is negative.</code></pre>
</p>
<p></details></p></li>
<li><p>Rewrite <code>sqrt_sum()</code> to return a missing value (<code>NA</code>) any time the sum of the two numbers is negative and produce a warning message explaining why this happened.</p>
<details> <summary>Click for the solution</summary>
<p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">sqrt_sum <-<span class="st"> </span>function(x, y) {
if(<span class="kw">sum</span>(x, y) <<span class="st"> </span><span class="dv">0</span>) {
<span class="kw">warning</span>(<span class="st">"The sum of these numbers is negative."</span>)
<span class="kw">return</span>(<span class="ot">NA</span>)
}
<span class="kw">sqrt</span>(x +<span class="st"> </span>y)
}
<span class="kw">sqrt_sum</span>(<span class="dv">3</span>,-<span class="dv">6</span>)</code></pre></div>
<pre><code>## Warning in sqrt_sum(3, -6): The sum of these numbers is negative.</code></pre>
<pre><code>## [1] NA</code></pre>
</p>
<p></details></p></li>
</ol>
</div>
</div>
<div id="tracking-down-bugs-using-traceback" class="section level1">
<h1>Tracking down bugs using <code>traceback()</code></h1>
<p>Hadley writes a <a href="http://adv-r.had.co.nz/Exceptions-Debugging.html#debugging-tools">detailed breakdown of all the debugging tools available in RStudio</a>. Here I want to focus on one specific tool, the <strong>traceback</strong>.</p>
<div id="the-call-stack" class="section level2">
<h2>The call stack</h2>
<p>The <strong>call stack</strong> is the sequence of calls that lead up to an error. Remember that when you execute a function in R, that function relies on additional functions to complete your task. In order to determine which function generated the bug, we need to “trace back” through the call stack to find the problematic function.</p>
<p>Here’s a trivial example from <em>Advanced R</em>. Note the sequence of functions:</p>
<ul>
<li><code>f()</code> calls <code>g()</code></li>
<li><code>g()</code> calls <code>h()</code></li>
<li><code>h()</code> calls <code>i()</code></li>
<li><code>i()</code> adds together a number and a string, creating an error</li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">f <-<span class="st"> </span>function(a) <span class="kw">g</span>(a)
g <-<span class="st"> </span>function(b) <span class="kw">h</span>(b)
h <-<span class="st"> </span>function(c) <span class="kw">i</span>(c)
i <-<span class="st"> </span>function(d) <span class="st">"a"</span> +<span class="st"> </span>d
<span class="kw">f</span>(<span class="dv">10</span>)</code></pre></div>
<pre><code>## Error in "a" + d: non-numeric argument to binary operator</code></pre>
<p>Clearly the error is not generated by <code>f()</code>, yet at first glance all we know is that by executing <code>f()</code> we have generated an error. How could we view the call stack to determine the sequence of functions leading up to the error? Use <code>traceback()</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">traceback</span>()</code></pre></div>
<pre><code># 4: i(c) at exceptions-example.R#3
# 3: h(b) at exceptions-example.R#2
# 2: g(a) at exceptions-example.R#1
# 1: f(10)</code></pre>
<p>We read the call stack from bottom to top. The first call was <code>f(10)</code>, which calls <code>g()</code>, which calls <code>h()</code>, which calls <code>i()</code>, which triggers the error. If the code is saved in a file, R will also print the location where the function is saved using the format <code>filename.R#linenumber</code>.</p>
</div>
</div>
<div id="condition-handling" class="section level1">
<h1>Condition handling</h1>
<p>Unexpected errors should be hunted down and destroyed. Well, maybe they just require interactive debugging to figure out what went wrong so you can revise the code to avoid the error. However in other instances you may have <strong>expected errors</strong>, or errors that don’t require interactive debugging, but instead just require automatic handling. This commonly occurs when you are fitting many statistical models to data sets, or iterating over a list or the columns of a data frame. In these situations you don’t want the entire iteration to fail because of a single element; instead, you want to complete the entire operation and then examine errors after the fact. There are three methods for condition handling I want to demonstrate and practice in this lesson:</p>
<ul>
<li><code>try()</code> allows you to continue execution even if a fatal error occurs</li>
<li><code>safely()</code> is an <strong>adverb</strong> that modifies functions to never throw an error; instead, any output, messages, warnings, and errors are captured as enhanced output.</li>
</ul>
<div id="ignore-errors-with-try" class="section level2">
<h2>Ignore errors with <code>try()</code></h2>
<p><code>try()</code> allows a function to continue execution even after a fatal error occurs. Recall that under normal circumstances, a fatal error immediately terminates a function and prevents the function from returning a value:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">f1 <-<span class="st"> </span>function(x) {
<span class="kw">log</span>(x)
<span class="dv">10</span>
}
<span class="kw">f1</span>(<span class="st">"x"</span>)</code></pre></div>
<pre><code>## Error in log(x): non-numeric argument to mathematical function</code></pre>
<p>If we wrap the statement that generates the error in <code>try()</code>, the error will be signalled, but execution of the function will continue.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">f2 <-<span class="st"> </span>function(x) {
<span class="kw">try</span>(<span class="kw">log</span>(x))
<span class="dv">10</span>
}
<span class="kw">f2</span>(<span class="st">"a"</span>)</code></pre></div>
<pre><code>## [1] 10</code></pre>
<p>To pass larger blocks of code, wrap them in <code>{}</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">try</span>({
a <-<span class="st"> </span><span class="dv">1</span>
b <-<span class="st"> "x"</span>
a +<span class="st"> </span>b
})</code></pre></div>
</div>
<div id="dealing-with-failure-using-safely" class="section level2">
<h2>Dealing with failure using <code>safely()</code></h2>
<p><code>try()</code> is part of base R and like its cousins <code>tryCatch()</code> and <code>withCallingHandlers()</code> has existed for years now. If you begin to write and develop your own functions on a regular basis you should familiarize yourself with and practice these condition handling methods. However I presume the vast majority of you, at least for the immediate future, will more likely rely on existing functions. When you encounter errors in these situations, you are not going to rewrite functions from packages like <code>dplyr</code> or <code>ggplot2</code>. Instead, you want a method of dealing with failure that doesn’t bring your code to a crashing halt.</p>
<p>Enter the <code>safely()</code> function. This function is an <strong>adverb</strong> in that it takes a function (a verb in <code>tidyverse</code> speak) and returns a modified version. The modified version never throws an error, but instead returns a list with two elements:</p>
<ol style="list-style-type: decimal">
<li><code>result</code> is the original result. If there was an error, then this will be <code>NULL</code>.</li>
<li><code>error</code> is an error object. If the operation was successful, then this will be <code>NULL</code>.</li>
</ol>
<p>This is quite similar to <code>try()</code>, but the result is more predictable. Let’s look at a basic function like <code>sqrt()</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">safe_sqrt <-<span class="st"> </span><span class="kw">safely</span>(sqrt)
<span class="kw">str</span>(<span class="kw">safe_sqrt</span>(<span class="dv">9</span>))</code></pre></div>
<pre><code>## List of 2
## $ result: num 3
## $ error : NULL</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(<span class="kw">safe_sqrt</span>(<span class="st">"a"</span>))</code></pre></div>
<pre><code>## List of 2
## $ result: NULL
## $ error :List of 2
## ..$ message: chr "non-numeric argument to mathematical function"
## ..$ call : language .f(...)