-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackages-part1.html
More file actions
962 lines (860 loc) · 36.5 KB
/
packages-part1.html
File metadata and controls
962 lines (860 loc) · 36.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>PSAW II: Packages Part 1</title>
<script src="site_libs/header-attrs-2.11/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/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>
<style>h1 {font-size: 34px;}
h1.title {font-size: 38px;}
h2 {font-size: 30px;}
h3 {font-size: 24px;}
h4 {font-size: 18px;}
h5 {font-size: 16px;}
h6 {font-size: 12px;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/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/lightable-0.0.1/lightable.css" rel="stylesheet" />
<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-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.tab('show');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
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">
<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">PSAW-2022</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-calendar"></span>
Workshop Notes
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="git-part1.html">
<span class="fa fa-cogs"></span>
Git Basics
</a>
</li>
<li>
<a href="git-part2.html">
<span class="fab fa-github-alt"></span>
GitHub Basics
</a>
</li>
<li>
<a href="git-part3.html">
<span class="fab fa-github"></span>
More Git Skills
</a>
</li>
<li>
<a href="rstudiocloud-part1.html">
<span class="fa fa-cloud"></span>
RStudio Cloud 1
</a>
</li>
<li>
<a href="rstudiocloud-part2.html">
<span class="fa fa-graduation-cap"></span>
RStudio Cloud 2
</a>
</li>
</ul>
</li>
<li>
<a href="https://rverse-tutorials.github.io/">
<span class="fa fa-folder"></span>
More Resources
</a>
</li>
<li>
<a href="aboutme.html">
<span class="fa fa-info"></span>
About Me
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/RVerse-Tutorials/PSAW-2022">
<span class="fab fa-github"></span>
Repo
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">PSAW II: Packages Part 1</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>
<p>In Part 1, I will discuss how to make an R package, with specific emphasis on data R packages, and show you how to document functions and data with Roxygen2.</p>
<p>By the end of this workshop, you will be able to build your own mini R package using RStudio. I’ll show you how to host it on GitHub with a nice little landing page.</p>
<p>If/when you want to go into R packaging in more depth, see Hadley Wickham’s book <a href="http://r-pkgs.had.co.nz/">R Packages</a>.</p>
<div id="why-a-package" class="section level2">
<h2>Why a package?</h2>
<div id="shorter-answer" class="section level3">
<h3>Shorter answer</h3>
<ul>
<li>The package framework really helps you write robust code and well documented code.</li>
<li>It makes it easy to bundle data with code.</li>
<li>It make it easy to version and document your data.</li>
</ul>
</div>
<div id="longer-answer" class="section level3">
<h3>Longer answer</h3>
<p>An R package is an easy and the standard way to organize your R code, document your code, and share your code with other people. Why use an R package rather than just make a bunch of scripts with your data in a folder?</p>
<ul>
<li><strong>Reproducibility and documentation</strong> In the long-run, you will save yourself much work if you organize and document your code. Rather than writing a series of scripts that you copy and alter for each project, you think about how to make your scripts into functions.</li>
<li><strong>You want to share your code</strong> If you are making code to that can be used for different data, rather than only your specific problem, then you want to make a package so that you can share your code.</li>
<li><strong>Robust data sharing!</strong> Putting your data in a dedicated data package allows you to version your data (so everyone knows they are using the most up to date data), document your data, track data changes, provide data releases (with archives), provide easy visualizations of the data, and any other packages can load that data package and have access to the data.</li>
<li><strong>You want to make an application</strong> If you want to make a shiny application, having your code in a package will help.</li>
</ul>
</div>
</div>
<div id="set-up-for-psaw-iii" class="section level2">
<h2>Set-up for PSAW III</h2>
<p>No set-up necessary. You only need a browser as we’ll be working using RStudio Cloud.</p>
<details>
<summary>
For RStudio users who want to do this on their computer
</summary>
<p>You’ll need to install {roxygen2}, {knitr}, {rmarkdown} at least.</p>
<p><strong>Mac users</strong>: You don’t need to do anything. Package building should just work.</p>
<p><strong>Windows users</strong>: Try running this code and see what happens. You need to install {devtools} package if you don’t have it.</p>
<pre><code># install.packages("devtools")
devtools::install_github("RVerse-Tutorials/TestPackage")</code></pre>
<p>If that code complains, then you need to install <a href="https://cran.r-project.org/bin/windows/Rtools/">RTools</a>. Note there is a different RTools for R 4.0.0 (released in April 2020) versus earlier R releases. Look for the little link for earlier versions of RTools if you don’t have 4.0.0 installed. Technically, it says you only need RTools to install packages with C/C++ so you might be fine. Personally, I always install RTools on my Windows machines since I install packages with C/C++ sometimes. But to keep things simple, try building a package without RTools and see if it works.</p>
</details>
</div>
<div id="a-simple-package" class="section level2">
<h2>A simple package</h2>
<div id="on-rstudio-cloud" class="section level3">
<h3>On RStudio Cloud</h3>
<p>Open this link, <a href="https://rstudio.cloud/project/3592671">TestPackage</a></p>
<details>
<summary>
Click to see how to do this in RStudio your computer
</summary>
<p>This makes a basic package using RStudio on your computer but it won’t be exactly like TestPackage.</p>
<ol style="list-style-type: decimal">
<li>Open RStudio</li>
<li>In the upper right hand corner, click the blue cube with R, and click New Project.</li>
<li>Click ‘New Directory’ and choose R package.</li>
<li>Name your package <code>TestPackage</code> and select the directory where to put it.</li>
<li>Click Create Package.</li>
<li>Click on the ‘Build’ tab in the upper right, and click ‘Install and Restart’. Your package should build and load.</li>
<li>Click on click ‘check’. Your package should pass all the checks without errors.</li>
</ol>
</details>
</div>
</div>
<div id="parts-of-an-r-package" class="section level2">
<h2>Parts of an R package</h2>
<div id="the-essentials" class="section level3">
<h3>The essentials</h3>
<p>2 files and a directory.</p>
<ul>
<li><p><strong>DESCRIPTION</strong> This file has the meta-data about your package. Name and what packages it depends on. Most of it is self-explanatory. The <code>Depends:</code> and <code>Imports:</code> lines specify any functions from other packages that you use in your functions.</p></li>
<li><p><strong>NAMESPACE</strong> This file indicates what needs to be exposed to users for your R package. For our course, you won’t need to edit as {roxygen2} takes care of it.</p></li>
<li><p><strong>R directory</strong> This is where all your R code goes for your package.</p></li>
</ul>
</div>
<div id="basic-add-ons" class="section level3">
<h3>Basic add-ons</h3>
<ul>
<li><p><strong>man</strong> A directory for documentation. You won’t need to write this. It will be added automatically by {roxygen2}.</p></li>
<li><p><strong>data</strong> A directory for data files saved in RData format with the ending <code>.rda</code> or <code>.RData</code>. Nothing else!</p></li>
</ul>
</div>
<div id="other-add-ons" class="section level3">
<h3>Other add-ons</h3>
<ul>
<li><p><code>inst</code> folder for misc stuff</p></li>
<li><p><code>inst\extdata</code> folder for external data.</p></li>
<li><p><code>data-raw</code> A directory for raw data files that produced the data files in <code>data</code> folder.</p></li>
<li><p><code>.Rbuildignore</code> optional, but in practice you will always need this.</p></li>
</ul>
</div>
</div>
<div id="lets-add-to-testpackage" class="section level2">
<h2>Let’s add to TestPackage</h2>
<div id="double-check-that-project-options-are-correct" class="section level3">
<h3>Double-check that Project Options are correct</h3>
<ol style="list-style-type: decimal">
<li><p>Click on Tools > Project Options > Build Tools</p></li>
<li><p>Make sure Generate documentation with Roxygen is checked. <em>Don’t see that?</em> Then you need to install the {roxygen2} package.</p></li>
<li><p>Click Configure next to the Roxygen line. Make sure all the checkboxes are checked. The last 2 won’t be by default.</p></li>
</ol>
</div>
<div id="add-a-function-to-testpackage" class="section level3">
<h3>Add a function to TestPackage</h3>
<ol style="list-style-type: decimal">
<li><p>Create a new R script file. File > New File > R Script.</p></li>
<li><p>Paste this code into the script and save as <code>hello.R</code> in the R directory.</p></li>
</ol>
<pre><code>#' Hello!
#'
#' This just says hello.
#' @export
hello <- function(){ cat("HELLO") }</code></pre>
<ol start="3" style="list-style-type: decimal">
<li><p>Click Install and Restart from the Build tab.</p></li>
<li><p>Click Check from the Build tab to make sure we didn’t make any errors.</p></li>
</ol>
</div>
<div id="use-your-new-function" class="section level3">
<h3>Use your new function</h3>
<p>Learn about your function with</p>
<pre><code>?hello</code></pre>
<p>Use your function with</p>
<pre><code>hello()</code></pre>
</div>
</div>
<div id="add-data" class="section level2">
<h2>Add data</h2>
<ol style="list-style-type: decimal">
<li><p>Add a folder called <code>data</code></p></li>
<li><p>Run these lines from the command line.</p></li>
</ol>
<pre><code>WWW2 <- WWWusage^2
save(WWW2, file="data/WWW2.rda")</code></pre>
<ol start="3" style="list-style-type: decimal">
<li><p>Click Install and Restart from the Build tab</p></li>
<li><p>Now your data are available from your package. Type</p></li>
</ol>
<pre><code>WWW2
littleforecast(WWW2)</code></pre>
<p>at the command line.</p>
</div>
<div id="the-key-components" class="section level2">
<h2>The key components</h2>
<div id="the-description-file" class="section level3">
<h3>The DESCRIPTION file</h3>
<p>Open the file named DESCRIPTION. Most of it is self-explanatory.</p>
<ul>
<li><code>Depends:</code> means the user will have all the commands of that package at the command line.</li>
<li><code>Imports:</code> is any other R packages that your package needs in order to work but it’s functions won’t be available at the command line (unless you choose).</li>
</ul>
<pre><code>Package: TestPackage
Title: This Is A Toy Package
Version: 1.3
Author: Eli Holmes
Maintainer: <[email protected]>
Description: This is a super simple toy package for students to copy and experiment with for the short course.
Depends: R (>= 3.4.1)
Imports: forecast, ggplot2
License: GPL-2
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.1.2</code></pre>
<p>The packages on the Depends and Imports lines are required to be installed in order to install your package. If the user doesn’t have these packages, then they will be installed when installing the package. When you try to Build and Install, R will complain and throw an error if you are missing packages.</p>
</div>
<div id="the-namespace-file" class="section level3">
<h3>The NAMESPACE file</h3>
<p>This file has the commands to export the functions (in the R folder) to the command line for use. If you don’t have a function here, the user will need to use <code>:::</code> to access the function.</p>
<p>We will use {roxygen2} to make our NAMESPACE file.</p>
<pre><code>exportPattern("^[[:alpha:]]+")
export(littleforecast)</code></pre>
<p>The first line means “export all functions”. The next line is exporting the <code>littleforecast</code> function.</p>
<p>How does {roxygen2} know to export a function? Add this to the documentation code at the top of your functions.</p>
<pre><code>#' @export</code></pre>
</div>
<div id="the-r-directory-function-code" class="section level3">
<h3>The R Directory: Function code</h3>
<p>This is where functions are put <strong>and our data documentation files</strong>. Each file is a separate function. You can put multiple functions in one file, but that can get confusing unless they are small functions. The top of the function has documentation in {roxygen2} format.</p>
<pre><code>#' @title A little foo function
#'
#' @description This little function does this.
#'
#' @param arg1 what this argument is
#' @export foo
foo <- function(arg1){
# The work
return(<what you want to return to user>)
}</code></pre>
</div>
<div id="rbuildignore" class="section level3">
<h3><code>.Rbuildignore</code></h3>
<p>Though not required, in practice you will need to tell R what not to include in your package. RStudio will make this for you but you need to check it and add more stuff.</p>
<pre><code>^.*\.Rproj$
^\.Rproj\.user$
^TestPackage\.Rcheck$
^TestPackage.*\.tar\.gz$
^TestPackage.*\.tgz$
.github
.git</code></pre>
</div>
</div>
<div id="lets-add-another-function-to-testpackage" class="section level2">
<h2>Let’s add another function to TestPackage</h2>
<ol style="list-style-type: decimal">
<li><p>Create a new R script file. File > New File > R Script.</p></li>
<li><p>Paste this code into the script and save as <code>hello.R</code> in the R directory.</p></li>
</ol>
<pre><code>#' dplyr example
#'
#' This adds a new function that needs {dplyr}
#' @param col which column to average
#' @export
irisaverages <- function(col = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")){
col <- match.arg(col)
iris$col <- iris[[col]]
iris %>% dplyr::group_by(Species) %>%
dplyr::summarize(mean = mean(col))
}</code></pre>
<p>We now use {dplyr} and <code>%>%</code> (pipe).</p>
<p>We can either add {dplyr} to <code>Depends</code> in our DESCRIPTION file but that would load the whole {dplyr} library and maybe we don’t want to do that.</p>
<p>We can add {dplyr} to <code>Imports</code> but how to get <code>%>%</code>? Add a file <code>import_packages.R</code> to the R folder (the name of the file is unimportant).</p>
<pre><code>#' @importFrom magrittr %>%
NULL</code></pre>
<p><em>How would I ever remember this??</em> Sadly if your use piping, you’ll gets lots of practice with this.</p>
</div>
<div id="data-package-in-r" class="section level2">
<h2>Data package in R</h2>
<p>Open this link, <a href="https://rstudio.cloud/project/3592413">ToyDataPackage</a></p>
<p>A data package can be exactly the same as a code package except that you don’t have much in the <code>R</code> folder and you have a lot in the <code>data</code> folder. A “data” package is just dedicated to data. There is nothing else very special about it.</p>
<div id="new-parts-of-the-package" class="section level3">
<h3>New parts of the package</h3>
<ol style="list-style-type: decimal">
<li>A <code>data-raw</code> folder. Optional but can but used for the raw data.</li>
<li><code>data</code> folder. Required. Your data save as <code>rda</code> or <code>RData</code>.</li>
<li>An R script in the <code>R</code> folder with documentation for your data.</li>
</ol>
</div>
<div id="example" class="section level3">
<h3>Example</h3>
<pre><code>cars2 <- read.csv("data-raw/cars2.csv", row.names=1)
save(cars2, file="data/cars2.rda")</code></pre>
<p>And then in the R folder is <code>data-cars2.R</code>. Tip, it is good to give your data documentation scripts a clear name tag to distinguish them from functions.</p>
<pre><code>#' @title a dataset of horsepower for different cars
#'
#' @description First 4 columns of the mtcars dataset.
#'
#' \itemize{
#' \item mpg. miles per gallon
#' \item cyl. cylinders
#' \item disp. displacement
#' \item hp. horse poser
#' }
#'
#' @docType data
#' @name cars2
#' @usage data(cars2)
#' @references R base package.
#' @format A data frame.
#' @keywords datasets
NULL</code></pre>
<p><em>Note</em>, in the latest Roxygen2, you don’t need the <code>@name</code> but that only works if you use <code>LazyData: true</code> in your <code>DESCRIPTION</code> file. For a pure data package, you might not want to do that.</p>
<ol start="5" style="list-style-type: decimal">
<li>Click Install and Restart from the Build tab.</li>
</ol>
<p>Let’s use our new data package in a R Markdown document.</p>
<pre><code>---
title: "Untitled"
output: html_document
---
```{r}
library(ToyDataPackage)
```
```{r, echo=FALSE}
library(ToyDataPackage)
data(cars2)
knitr::kable(cars2,
caption=paste("This is version", packageVersion("ToyDataPackage')))
```</code></pre>
</div>
</div>
<div id="file-names-data-names-and-documentation" class="section level2">
<h2>File names, data names and documentation</h2>
<div id="rda-file-names" class="section level3">
<h3><code>rda</code> file names</h3>
<p>The <code>rda</code> filename in the <code>data</code> folder is what is used to load data. For example, let’s say you have</p>
<pre><code>save(cars1, cars2, file="data/carsdata.rda")</code></pre>
<p>So 2 data objects saved to one <code>rda</code> file. To load both data objects, you use</p>
<pre><code>data(carsdata)</code></pre>
</div>
<div id="data-documentation" class="section level3">
<h3>Data documentation</h3>
<p>What do I document: <code>cars1</code>, <code>cars2</code> or <code>carsdata</code>? You can actually do whatever you want.</p>
<p>Do this to show this documentation with <code>?cars2</code>.</p>
<pre><code>#' @title a dataset of horsepower for different cars
#'
#' @docType data
#' @name cars2
NULL</code></pre>
<p>Do this to show this documentation with <code>?cars1</code>, <code>?cars2</code>, and <code>?carsdata</code></p>
<pre><code>#' @title some datasets of horsepower for different cars
#'
#' @docType data
#' @name carsdata
#' @aliases cars1 cars2
NULL</code></pre>
<p>Do this to show this documentation with <code>?carsdata</code>.</p>
<pre><code>#' @title three datasets of horsepower for different cars
#'
#' @docType data
#' @name carsdata
NULL</code></pre>
<p>This will only work for data that are exported. That means <code>Lazydata: true</code> and what is loaded from <code>data(carsdata)</code>.</p>
<pre><code>#' @title three datasets of horsepower for different cars
#'
#' @docType data
"cars2"</code></pre>
<p>So this fails since it is not <code>carsdata</code> that is exported. That is just the name of the data file.</p>
<pre><code>#' @title three datasets of horsepower for different cars
#'
#' @docType data
"carsdata"</code></pre>
</div>
</div>
<div id="changes-to-that-workflow" class="section level2">
<h2>Changes to that workflow</h2>
<ul>
<li><em>Can I have multiple data objects saved to one <code>rda</code> file?</em> Yes. Use <code>@alias</code> in your Roxygen2 file (in the R folder) to use the same documentation for each data object or create separate documentation files for each data object.</li>
<li><em>My data is not csv files.</em> That was just an example. For documentation purposes, it is now recommended to use <code>data-raw</code> so that you have the raw data and the <code>rda</code> files in the <code>data</code> directory. You can put whatever you want into <code>data-raw</code>.</li>
<li><em>Won’t including the raw data make my R package huge?</em> Yes, it would. In your <code>.Rbuildignore</code> file, add the line <code>^data-raw$</code> to not include that in a build.</li>
<li><em>Would you always put raw data in <code>data-raw</code>?</em> No. Another common place is <code>inst\extdata</code>. Which one you use is up to you. I use <code>extdata</code> more as a sandbox and it will have all sorts of info used to make the <code>data</code> files.</li>
<li><em>My data are huge or the raw data should not be on any repo. I don’t want them part of the package at all.</em> That’s fine. You only need the <code>data</code> folder.</li>
</ul>
</div>
<div id="comment-on-roxygen2-headers-for-data" class="section level2">
<h2>Comment on Roxygen2 headers for data</h2>
<p>The <a href="https://r-pkgs.org/index.html">R Packages</a> section on <a href="https://r-pkgs.org/data.html#documenting-data">documenting data</a> shows you how to write your Roxygen2 code to document data.</p>
<p>But keep the following in mind. The Roxygen2 code that is shown in the R Packages book above is the “new” style which needs <code>LazyData: true</code> in your <code>DESCRIPTION</code> file. Here’s how the new Roxygen2 code looks. Notice no <code>@name mydata</code> and <code>NULL</code> at the bottom is replaced with <code>"mydata"</code>.</p>
<pre><code>#' @title My Data
#'
#' @description My dataset on diamonds and here is more info.
#'
#' \itemize{
#' \item price. price in US dollars
#' \item carat. weight of the diamond
#' }
#'
#' @docType data
#' @usage data(mydata)
#' @format A data frame with 10 rows and 2 variables
"mydata"</code></pre>
<p>If you changed <code>LazyData: false</code>, all that Roxygen2 code is going to fail. So I personally would never use the new Roxygen2 “shortcut”.</p>
<p>Why would you ever set <code>LazyData: false</code>? Because some of your data have the same name. I make R data packages with 100s of datasets with the exact same structure and same name. I use them like so where <code>dat</code> is a character string name of my data:</p>
<pre><code>plot_data <- function(dat){
data(dat)
gpplot(salmon, aes(x=year, y=spawners)) + geom_point()
}</code></pre>
<p>All my data are stored with the name <code>salmon</code> not with the data file name.</p>
<p>So like so:</p>
<pre><code>salmon <- read.csv(file="data-raw/columbia-river-chinook-esu.csv")
save(salmon, file="data/columbia-river-chinook-esu.rda")</code></pre>
<p>I don’t ever want to refer to the Columbia River data as <code>columbia-river-chinook-esu</code>. In my workflow, that wouldn’t make sense.</p>
<p>But in other applications, it often makes sense to give your data a specific name, like <code>sst</code> or <code>nooksack-river</code> or <code>thedata</code>. In that case, the style in the R Packages section on <a href="https://r-pkgs.org/data.html#documenting-data">documenting data</a> is fine.</p>
</div>
<div id="examples-of-real-data-packages" class="section level2">
<h2>Examples of real data packages</h2>
<ul>
<li><a href="https://github.com/eeholmes/SardineForecast">SardineForecast</a> A complex package with lots of different types of data.</li>
<li><a href="https://nwfsc-math-bio.github.io/VRData/">VRData</a> This is a data repo that I am developing for NWFSC application.</li>
</ul>
</div>
<div id="creating-your-own-r-package" class="section level2">
<h2>Creating your own R package</h2>
<div id="the-base-package" class="section level3">
<h3>The base package</h3>
<ul>
<li>Create a new R package in RStudio via New Project in upper right corner.</li>
<li>Once you select New Project, select New Directory > R package. That will create a template for your.</li>
<li>Install the {roxygen2} package if needed.</li>
<li>Open Tools > Project Options > Build Tools. Then click the checkbox to create documentation with roxygen2. Next click Configure and make sure all the checkboxes are checked (all of them)</li>
<li>Delect NAMESPACE since you are going to have {roxygen2} make this.</li>
<li>From the Build tab, click ‘Install and Restart’. Now the {roxygen2} info will be added to your DESCRIPTION file and {roxygen2} will make your NAMESPACE</li>
<li>Go into the R folder and replace the <code>hello.R</code> code with this so you have a better starting template. Later you will develop your own {roxygen2} template so you don’t have to remember how to document a function.</li>
</ul>
<pre><code>#' This is the title
#'
#' This is the description
#'
#' @param arg1 describe what arg1 is
#'
#' @export
#' @keywords functions
hello <- function(arg1) {
print("Hello, world!")
}</code></pre>
</div>
<div id="add-functions-to-your-package" class="section level3">
<h3>Add functions to your package</h3>
<ul>
<li>Add <code>.R</code> files to the <code>R</code> folder with your {roxygen2} header.</li>
</ul>
</div>
<div id="add-data-to-your-package" class="section level3">
<h3>Add data to your package</h3>
<ul>
<li>Create <code>data</code> folder.</li>
<li>Add <code>.rda</code> (or <code>.RData</code> doesn’t matter which) files to the <code>data</code> folder.</li>
<li>Add documentation files for your data objects in the R folder. The file should have <code>.R</code> ending but the filename doesn’t matter. I suggest something like <code>data-dataname.R</code>. Using <code>data-</code> tag will help you find all your data documentation files.</li>
</ul>
<p>If you use <code>LazyData: true</code> and your data all have unique names, your data documentation file (e.g. <code>data-dataname.R</code> which you put in the R folder) can take the form:</p>
<pre><code>#' title
#'
#' data description
#'
"dataname"</code></pre>
<p>where <code>dataname</code> is the name of the data object. Note {roxygen2} will throw an error if <code>dataname</code> is not a loaded data object in your <code>data</code> folder.</p>
<p>If you use <code>LazyData: false</code>, your data do not have unique names, or you want more flexibility in creating your data documentation, use something like this for your data documentation file:</p>
<pre><code>#' title
#'
#' data description
#'
#' @docType data
#' @name dataname
NULL</code></pre>
<p>The <code>@name</code> part specifies what name will call up help when the users types <code>?dataname</code>. <code>dataname</code> does not need to exist as an object. You can use any text you want.</p>
<p>Want the same documentation to come up for multiple names? For example, the same documentation page to appear for <code>?species1</code> and <code>?species2</code> and <code>?surveydata</code>? Use <code>@aliases</code> like so</p>
<pre><code>#' @name surveydata
#' @aliases species1 species2</code></pre>
<p>Note, if you want to keep your raw data and code to convert that into the <code>rda</code> files with the package, put in <code>data-raw</code>. To keep that directory out of the package that users install, add <code>data-raw</code> to the <code>.Rbuildignore</code> file.</p>
</div>
<div id="checking-your-package" class="section level3">
<h3>Checking your package</h3>
<ul>
<li>Run Check from the Build tab regularly. It is best not to put this off too long or else you’ll create a lot more work for yourself as you track down one warning or error after another.</li>
<li>Don’t let yourself suffer trying to figure out what the warnings and errors mean. Most are simple namespace issues that are easy to fix once you know how. Ask someone who builds packages. The NMFS R UG Group Chat is a good place.</li>
</ul>
</div>
</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.odd').parent('tbody').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 () {
// temporarily add toc-ignore selector to headers for the consistency with Pandoc
$('.unlisted.unnumbered').addClass('toc-ignore')
// 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>