-
Notifications
You must be signed in to change notification settings - Fork 0
/
packages.qmd
874 lines (629 loc) · 30.5 KB
/
packages.qmd
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
# Packages {#sec-pkgs}
```{r}
#| eval: true
#| echo: false
#| include: false
source("_common.R")
```
```{r}
#| label: co_box_tldr
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "b",
look = "default", hsize = "1.10", size = "1.05",
header = "![](images/rpkg_icon_no_bkgrnd.png){height=40} TLDR ",
fold = TRUE,
contents = "
<br>
Functional packages require three things:
1. A `DESCRIPTION` file with the following fields:\n
\`\`\`bash
Package
Version
License
Description
Title
Author
Maintainer
\`\`\`
2. An `Rproj` file with the following fields:\n
\`\`\`bash
BuildType: Package
PackageUseDevtools: Yes
PackageInstallArgs: --no-multiarch --with-keep.source
\`\`\`
  Access these settings via **Tools** > **Project Options** > **Build Tools**
3. `devtools` installed\n
\`\`\`r
install.packages('devtools')
library(devtools)
\`\`\`
"
)
```
---
::: {layout="[85, 15]" layout-valign="top"}
This chapter covers the necessary ingredients of R packages. We'll start by exploring the differences between Shiny projects, R packages, and Shiny app-packages. Then, we'll dive into the requirements for 1) creating new Shiny app-packages, and 2) converting Shiny app projects into Shiny app-packages.
![](images/rpkg_icon_no_bkgrnd.png){fig-align="right" width='100%'}
:::
:::: {.callout-tip collapse='true' appearance='default' icon=false}
## [Accessing applications]{style='font-weight: bold; font-size: 1.15em;'}
::: {style='font-size: 0.95em; color: #282b2d;'}
I've created the [`shinypak` R package](https://mjfrigaard.github.io/shinypak/) In an effort to make each section accessible and easy to follow:
Install `shinypak` using `pak` (or `remotes`):
```{r}
#| code-fold: false
#| message: false
#| warning: false
#| eval: false
# install.packages('pak')
pak::pak('mjfrigaard/shinypak')
```
Review the chapters in each section:
```{r}
#| code-fold: false
#| message: false
#| warning: false
#| collapse: true
library(shinypak)
list_apps(regex = '^03')
```
Launch the app:
```{r}
#| code-fold: false
#| eval: false
launch(app = "03.3_create-package")
```
Download the app:
```{r}
#| code-fold: false
#| eval: false
get_app(app = "03.3_create-package")
```
:::
::::
Before we start, we should establish some operational definitions of what is meant by the terms 'project', 'package', and 'app-package'.
- ![](images/rproj_icon.png){height=30} **Shiny Projects**
- This book will consider a Shiny app project to be a directory containing a Shiny application (in an `app.R` file or `ui.R`/`server.R` files)
- Shiny projects also include a Posit workbench project file (`.Rproj`)
- ![](images/rpkg_small_v2.png){height=30} **R Packages**
- I'll use the term **R package** to describe a directory of functions, documentation, or data that can be successfully installed and loaded into an R session
- An R package includes the necessary dependency management (`NAMESPACE`), metadata files (`DESCRIPTION`), Posit workbench project file (`.Rproj`), *and* has access to the package development tools in Posit Workbench
- ![](images/shinyap_small_v2.png){height=30} **Shiny app-packages**
- A **Shiny app-package** (which you have probably already guessed) is an R package containing a Shiny application
- Shiny app-packages have all of the functionality of a standard R Package but also contain the files and folders required to successfully develop, run, and deploy a Shiny app
:::{.column-margin}
I'll differentiate Shiny app projects, R packages, and Shiny app-packages using icons
:::
There are multiple reasons for deciding to develop a Shiny app-package, but if you're reading this book, you've likely found yourself in one of two circumstances:
1. You want to develop a new app, but want it structured as an R package![](images/rpkg_small_v2.png){height=30}.
2. You've already developed a Shiny app project![](images/rproj_icon.png){height=30}, but now you need to convert it to a Shiny app-packages![](images/shinyap_small_v2.png){height=30}
The previous chapters covered a few practices to adopt during development that improve the extensibility of your app and will make it easier to convert into a Shiny app-package.[^pkgs-shiny-development]
[^pkgs-shiny-development]: Shiny app project features are covered in @sec-shiny-folders and @sec-shiny-files of the previous chapter.
## Development Environment {#sec-pkgs-ides}
![](images/rstudio-icon.png){height=30} RStudio (developed by [Posit, PBC](https://posit.co/)) is a popular integrated development environment (IDE) that streamlines many R package development tasks. I’ve purposely connected RStudio to the definitions above for R package and Shiny app-packages. Specifically, the package development tools provided in the **Build** pane and the `devtools` package.
Posit has recently released a new IDE: ![](images/positron.png){height=30} [Positron.](https://github.com/posit-dev/positron). **This IDE is under active development**, so most of the chapters will focus on developing Shiny app-packages in the RStudio IDE. Future chapters will include descriptions of Positron if the development process or features are significantly different from RStudio.
Developing R packages in RStudio (or using `.Rproj` files) is not required. There are alternative package development tools and processes outside of Posit Workbench, and many developers employ these setups.
Package development outside RStudio would look almost identical to development in the IDE:
1. Create the package structure (`R/` folder for `.R` scripts, `man/` folder for documentation, `data/` folder for datasets, etc.)
2. Create `DESCRIPTION` and `NAMESPACE` files, etc.
3. Ensure the package can be installed and loaded into an R session.
It’s also possible to use many of the development workflow functions we’ll cover here outside of the IDE (`roxygen2::roxygenize()`, `devtools::check()`, `devtools::install()`, etc.).
## R packages ![](images/rpkg_small_v2.png){height=45}
R packages can be easily shared, reused, and reproduced because they all have a familiar structure, and each folder and file plays an essential role in extending R’s capabilities.[^pkgs-folder-trees]
Below is a folder tree with some of the typical files and folders found in R packages:
```{bash}
#| eval: false
#| code-fold: false
#| echo: true
<R package>/
├── DESCRIPTION
├── <R package>.Rproj
├── LICENSE
├── LICENSE.md
├── NAMESPACE
├── NEWS.md
├── README.Rmd
├── README.md
├── renv.lock
├── R/
├── man/
├── tests/
├── data/
├── data-raw/
├── vignettes/
├── inst/
└── renv/
```
[^pkgs-folder-trees]: Fortunately, Shiny app-packages don't require *all* the files and folders displayed in the folder tree to gain the functionality and benefits of an R package.
This chapter will cover the minimum requirements for an R package, so you can handle both creating new Shiny app-packages and converting existing Shiny projects into Shiny app-packages.
### *Functional* R packages {#sec-packages-essential-ingredients}
If you've done some research on R packages, you've probably encountered one (or both) of the following statements,
> *'RStudio [Posit Workbench] and `devtools` consider any directory containing `DESCRIPTION` to be a package'* - [R Packages, 2ed (Chapter 9, `DESCRIPTION`)](https://r-pkgs.org/description.html#the-description-file)
>
> *'all a project needs to be a package is a directory of `R/` files and a `DESCRIPTION` file.'* - [Mastering Shiny (Chapter 20, Packages)](https://mastering-Shiny.org/scaling-packaging.html#summary-18)
The `sap` directory has:
::: {layout="[45,55]" layout-valign="top"}
### {.unnumbered}
- [x] an `.Rproj` project file
- [x] a `DESCRIPTION` file
- [x] an `R/` directory
```{bash}
#| eval: false
#| code-fold: false
sap/
├── DESCRIPTION # <1>
├── sap.Rproj # <2>
├── R/ # <3>
│ ├── mod_scatter_display.R
│ ├── mod_var_input.R
│ └── utils.R
├── README.md
├── app.R
├── movies.RData
└── www/
└── shiny.png
4 directories, 9 files
```
1. `DESCRIPTION` file
2. `.Rproj` file
3. `R/` folder with `.R` files
:::
So, is `sap` a functioning R package?
#### Can we load it with [`devtools`]{style="font-size: 1.05em; font-weight: bold;"}?
Package development kicks off with the `load_all()` function from `devtools`, which is similar to calling `library()` (we'll cover this function extensively in the `devtools` chapter).
However, when we attempt to load the code in the `R/` folder with `load_all()`, we see the following error:
```{r}
#| eval: false
#| code-fold: false
install.packages("devtools")
library(devtools)
devtools::load_all()
```
::: {#fig-pkgs_load_all_error}
![Load All Error](images/pkgs_load_all_error.png){#fig-pkgs_load_all_error width="100%" fig-align="center"}
`devtools` is looking for the **`Package` field** in our `DESCRIPTION` file
:::
#### Can we use the **Build** pane?
If you're using the RStudio IDE, then functioning R packages also have access to the **Build** pane, which allows us to quickly load, install, and test code.
When we open `sap`, the **Build** pane is not displayed in the IDE:
::: {#fig-pkgs_no_build_pane}
![`sap` IDE](images/pkgs_no_build_pane.png){#fig-pkgs_no_build_pane width="100%" fig-align="center"}
The **Build** pane is normally between **Connections** and **Git**.
:::
As we've just learned, the presence of the `DESCRIPTION` file and an `R/` folder are insufficient to turn a Shiny app project into a *functioning* R package that can be installed and loaded into an R session *and* has access to the **Build** pane in the IDE.
> "*A project needs **a `DESCRIPTION` file with specific fields**, a directory of `R/` files, and **a properly configured `.Rproj` file** to be a **functioning** R package.*"
Let's see how each of these requirements work together to convert the contents of `sap` from a Shiny project into a Shiny app-package.
### Does it have a [`DESCRIPTION`]{style="font-size: 1.05em; font-weight: bold;"}?
```{r}
#| label: git_box_3.1_description
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = "launch",
fig_pw = '75%',
branch = "03.1_description",
repo = 'sap')
```
The official R documentation[^pkgs-9] lists the following required fields for the `DESCRIPTION` in R packages:
[^pkgs-9]: The mandatory fields are covered in [Writing R Extensions, 'The DESCRIPTION file'](https://cran.r-project.org/doc/manuals/r-release/R-exts.html#The-DESCRIPTION-file)
> *The ‘Package’, ‘Version’, ‘License’, ‘Description’, ‘Title’, ‘Author’, and ‘Maintainer’ fields are mandatory.*
Below is an example `DESCRIPTION` file for our new `sap` package with the mandatory fields:[^pkgs-10]
[^pkgs-10]: Always leave an empty final line in the `DESCRIPTION` file.
```{bash}
#| eval: false
#| code-fold: false
Package: sap
Title: Shiny App-Packages
Version: 0.0.0.9000
Author: John Smith [aut, cre]
Maintainer: John Smith <[email protected]>
Description: An R package with a collection of Shiny applications.
License: GPL-3
```
::: {.callout-tip title="`Author` and `Maintainer` fields" collapse='true'}
Note that the `Author` and `Maintainer` fields require additional information beyond first and last name (i.e., `John Smith`). These can be created with the `utils::person()` function:
```{r}
#| collapse: true
#| code-fold: false
#| code-summary: 'show/hide person() output'
# Author
utils::person(
given = "John",
family = "Smith",
role = c("aut", "cre"))
# Maintainer
utils::person(
given = "John",
family = "Smith",
email = "[email protected]")
```
:::
After adding the mandatory fields to the `DESCRIPTION` file, `devtools::load_all()` runs without the previous error, but the IDE still doesn't display the **Build** pane:
:::: {.column-body-outset-right}
::: {#fig-pkgs_desc_no_build_pane}
![`sap` IDE](images/pkgs_desc_no_build_pane.png){#fig-pkgs_desc_no_build_pane height="100%" width="100%" fig-align="center"}
[Where is the **Build** pane?]{style="font-style: italic; font-size: 1.10em;"}
:::
::::
## R Projects ![](images/rproj_icon.png){height=45}
`.Rproj` files are plain text files with various settings for the IDE. We were able to run `devtools::load_all()` above *without* the presence of the **Build** pane because the IDE displays the **Build** pane after reading the fields in the `.Rproj` file.
The quickest way to access the fields in the `.Rproj` file is under **Tools** > **Project Options...**.
### R Project options
**Tools** > **Project Options...** provide access to the project-level options. For example, fields 2 - 4 are available under **General**, 5 - 8 affect the **Code** options, and the final two fields deal with **Sweave**.
::: {#fig-pkgs_proj_options}
![`sap.Rproj` fields](images/pkgs_proj_options.png){#fig-pkgs_proj_options width="100%" fig-align="center"}
Field settings from `sap.Rproj` file
:::
The default settings were created when we selected the Shiny app project from the **New Project Wizard** in the last chapter.
### Build tools
I've placed the `.Rproj` file from `sap` with the example `.Rproj` file from [R Packages, (2ed)](https://r-pkgs.org/) side-by-side so you can compare them below:[^pkgs-11]
[^pkgs-11]: `.Rproj` files are covered in the [What makes an RStudio Project? section of R Packages (2 ed)](https://r-pkgs.org/workflow101.html#what-makes-an-rstudio-projec)
::: {#fig-pkgs_rproj_fields}
![`.Rproj` files](images/pkgs_rproj_fields.png){#fig-pkgs_rproj_fields width="100%" fig-align="center"}
Comparison of `sap.Rproj` file and `.Rproj` file in [R Packages, 2ed](https://r-pkgs.org/workflow101.html#what-makes-an-rstudio-project)
:::
I've circled the fields in the `.Rproj` file that illustrate it's configured to work with an R package. Note that in `sap`, the **Project build tools** are initially set to (**None**) under **Build Tools**:
::: {#fig-pkgs_proj_opts_build_tools}
![`sap.Rproj` build tools](images/pkgs_proj_opts_build_tools.png){#fig-pkgs_proj_opts_build_tools height="100%" width="100%" fig-align="center"}
Build tool settings in `sap.Rproj` file
:::
Changing the **Project build tools** option to **Package** will set the default **Build Tools** options:[^pkgs-12]
[^pkgs-12]: The initial **Build Tools** settings (i.e., **(None)**) should help explain the absence of any R package development fields in the `sap.Rproj` when we compared it to the version in [R Packages, 2ed](https://r-pkgs.org/workflow101.html#what-makes-an-rstudio-project) (i.e., `BuildType`, `PackageUseDevtools`, `PackageInstallArgs`, and `PackageRoxygenize`).
::: {#fig-pkgs_proj_opts_build_tools_pkg}
![Default package build tools](images/pkgs_proj_opts_build_tools_pkg.png){#fig-pkgs_proj_opts_build_tools_pkg height="100%" width="100%" fig-align="center"}
Default build tool settings
:::
The links between the **Build Tools** options and fields in `sap.Rproj` are in the figure below:
::: {#fig-pkgs_rproj_connect_build_tools}
![`sap.Rproj` build tool fields](images/pkgs_rproj_connect_build_tools.png){#fig-pkgs_rproj_connect_build_tools width="100%" fig-align="center"}
Default build tool settings in `sap.Rproj` file
:::
- `BuildType: Package` tells the IDE `sap` is an R package and triggers the **Build** pane.
- `PackageUseDevtools: Yes` links the options in the **Build** pane to the [`devtools` package](https://devtools.r-lib.org/).
- The `PackageInstallArgs` are complicated, but I've included some information about them in the callout block below (and you can read more in the [official R documentation](https://cran.r-project.org/manuals.html))
- The fourth option (`PackageRoxygenize`) is available under **Generate documentation with Roxygen** > **Use roxygen to generate**:
- These options affect the documentation in an R package. To match the example from [R Packages, 2ed](https://r-pkgs.org/workflow101.html#what-makes-an-rstudio-project) above, make sure **Rd files**, **Collate field**, and **NAMESPACE file** are selected and click **OK**.
::: {#fig-pkgs_roxygenize_on_build}
![`PackageRoxygenize` in `.Rproj` file](images/pkgs_roxygenize_on_build.png){#fig-pkgs_roxygenize_on_build width="100%" fig-align="center"}
`roxygen2` build settings
:::
After clicking **OK**, the IDE will automatically reboot, and the additional fields will be added to the bottom of the `sap.Rproj`:
```{r}
#| label: git_box_03.2_rproj
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = "launch",
branch = "03.2_rproj",
repo = 'sap')
```
```{bash}
#| eval: false
#| code-fold: false
Version: 1.0
RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default
EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8
RnwWeave: Sweave
LaTeX: XeLaTeX
BuildType: Package
PackageUseDevtools: Yes
PackageInstallArgs: --no-multiarch --with-keep.source
PackageRoxygenize: rd,collate,namespace
```
```{r}
#| label: co_rproj_package_install_args
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "g",
fold = TRUE,
look = "default", hsize = "1.10", size = "1.05",
header = "What is `--no-multiarch --with-keep.source`?",
contents = "
- `--no-multiarch`: refers to the option for the package installer to only compile the package for the architecture of the current R session. By default, R tries to compile packages for 32-bit and 64-bit architectures if running in a 64-bit R session on Windows. This flag can help avoid problems if a package can only be compiled on one architecture. Read more [here](https://cran.r-project.org/doc/manuals/r-release/R-admin.html#Checking-installed-source-packages).
- `--with-keep.source`: In R, when a function is created, its body can be stored in two ways: 1) as a parsed but unevaluated expression and 2) as a character string containing the function's source code. By default, only the parsed expression is kept. If `–with-keep.source` is specified, R will also keep the source code as a character string, which can be helpful for debugging and tools that analyze or modify source code. Read more [here](https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Tidying-R-code).
"
)
```
### The **Build** pane
When the new session starts, the new project-level options activate the **Build** pane in the IDE, and I can check the R package functionality by loading the code with **Build** > **Load All**
::: {#fig-pkgs_build_menu}
![Load the code in the `R/` folder](images/pkgs_build_menu.png){#fig-pkgs_build_menu width="100%" fig-align="center"}
Identical to running `devtools::load_all()`
:::
I should see the following in the **Console**:
```{verbatim}
#| eval: false
#| code-fold: false
ℹ Loading sap
```
There you have it--`sap` is a functional app-package!
### Functional app-packages
In a functional app-package ![](images/shinyap_small_v2.png){height=30}:
1. The `DESCRIPTION` file contains the seven mandatory fields[^desc-fields-mandatory], making running the necessary `devtools` functions possible.
[^desc-fields-mandatory]: The [mandatory fields](https://cran.r-project.org/doc/manuals/r-release/R-exts.html#The-DESCRIPTION-file) `DESCRIPTION` fields are: `Package`, `Version`, `License`, `Description`, `Title`, `Author`, and `Maintainer`
2. The `.Rproj` file contains the three package configuration fields[^pkg-config-fields], which makes the **Build** pane accessible and functional.
[^pkg-config-fields]: The `.Rproj` package configuration fields are `BuildType: Package`, `PackageUseDevtools: Yes`, and `PackageInstallArgs: --no-multiarch --with-keep.source`.
Think of the two items above as a two-part process: the `DESCRIPTION` requires specific fields, and the IDE requires `.Rproj` fields to trigger the **Build** pane.
:::: {.column-body-outset-right}
::: {#fig-pkgs_functional_app_pkg}
![**Shiny app-package** (with `DESCRIPTION` and **Build** pane)](images/pkgs_functional_app_pkg.png){#fig-pkgs_functional_app_pkg width="100%" fig-align="center"}
Fully functional **Shiny app-package**
:::
::::
## App-packages ![](images/shinyap_small_v2.png){height=45}
The Posit documentation lists the following way(s) to create R packages:[^pkgs-15a]
> 1. Call `usethis::create_package()`.
>
> 2. In Posit Workbench, do **File** > **New Project** > **New Directory** > **R Package**. This ultimately calls `usethis::create_package()`, so really there’s just one way.
>
[^pkgs-15a]: This information comes from the [Writing R Packages](https://docs.posit.co/ide/user/ide/guide/pkg-devel/writing-packages.html) documentation for Posit Workbench.
```{r}
#| label: git_box_03.3_create-package
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
fig_pw = '75%',
branch = "03.3_create-package",
repo = 'sap')
```
`create_package()` is a great option if you're looking for a way to quickly create or convert your Shiny project into a Shiny app-package. In the following sections I'll cover some suggestions for using `create_package()`.[^pkgs-16]
[^pkgs-16]: `usethis::create_package()` is covered in the ['Fundamental development workflows' chapter of R Packages, 2ed](https://r-pkgs.org/workflow101.html)
### New app-packages {#sec-create-new-app-packages}
If you haven't written any code and want to create a new Shiny app-package, [`create_package()`](https://usethis.r-lib.org/reference/create_package.html) is the quickest way to get started.
First, install `devtools`:
```{r}
#| eval: false
#| code-fold: false
install.packages("devtools")
library(devtools)
```
`devtools` automatically loads `usethis`
```{verbatim}
#| eval: false
#| code-fold: false
Loading required package: usethis
```
Assuming your current working directory is where you want your new Shiny app-package, call `usethis::create_package()` with the `path` argument set to `getwd()`
```{r}
#| eval: false
#| code-fold: false
usethis::create_package(path = getwd())
```
This call launches a series of actions:
- First, the active project is set to whatever was given to the `path` argument.
```{verbatim}
#| eval: false
#| code-fold: false
✔ Setting active project to 'path/to/newApp'
```
- The `R/` folder and `DESCRIPTION/` file are created:
```{verbatim}
#| eval: false
#| code-fold: false
✔ Creating 'R/'
✔ Writing 'DESCRIPTION'
```
- The `NAMESPACE` and `.Rproj` files are created:
```{verbatim}
#| eval: false
#| code-fold: false
✔ Writing 'NAMESPACE'
✔ Writing 'newApp.Rproj'
```
- The `.Rproj` is added to the `.Rbuildignore` file, the `.Rproj.user` folder is added to the `.gitignore` and `.Rbuildignore` files.
```{verbatim}
#| eval: false
#| code-fold: false
✔ Adding '^newApp\\.Rproj$' to '.Rbuildignore'
✔ Adding '.Rproj.user' to '.gitignore'
✔ Adding '^\\.Rproj\\.user$' to '.Rbuildignore'
```
- A new session is opened from the new `.Rproj` file:
```{verbatim}
#| eval: false
#| code-fold: false
✔ Opening 'path/to/newApp/' in new RStudio session
```
When the new session opens, `newApp` has the following contents:
```{bash}
#| eval: false
#| code-fold: false
newApp/
├── .Rbuildignore
├── .Rproj.user/
├── .gitignore
├── DESCRIPTION
├── NAMESPACE
├── R/
└── newApp.Rproj
```
You're now free to develop `newApp`. Store and document any `.R` files in the `R/` folder, edit the `DESCRIPTION` file with details about the application, read through [R Packages](https://r-pkgs.org/) and [Mastering Shiny](https://mastering-Shiny.org/), and add the Shiny code to complete your Shiny app-package.
### Converting a Shiny project {#sec-convert-shiny-app-packages}
If you already have a Shiny app project that needs to be converted into a Shiny app-package, you can also use `create_package(path = getwd())` in your root folder, but I recommend using the following arguments:
#### [`DESCRIPTION`]{style="font-size: 0.95em"} arguments
- **`fields`**: these are arguments passed to `usethis::use_description()`. If the `fields` argument is empty, a boilerplate `DESCRIPTION` file is created (similar to [this one](https://r-pkgs.org/description.html#the-description-file)).
- These boilerplate fields in the `DESCRIPTION` work, but I've found some of the fields are unnecessary (i.e., I've never needed `Authors@R:` or `ORCID`) and inevitably require revision, so I'd prefer to handle this during the creation process (and remove the risk of forgetting to change it later).
- All fields should be passed in a `list()` as `field = 'value'` pairs.
```{r}
#| eval: false
#| code-fold: false
usethis::use_description(
list(Package = 'sap',
Version = '0.0.0.9000',
Title = 'Shiny App-Packages',
Description = 'An R package with a collection of Shiny applications.',
"Authors@R" = NULL,
Author = utils::person(
given = "John",
family = "Smith",
role = c("aut", "cre")),
Maintainer = utils::person(
given = "John",
family = "Smith",
email = "[email protected]"),
License = "GPL-3"))
```
- A few fields require specially formatted values (see the `utils::person()` examples below).
```{r}
#| eval: true
#| code-fold: false
utils::person("John", "Smith",
email = "[email protected]",
role = c("aut", "cre"))
```
- Two additional arguments from `use_description()` are passed to `create_package()`:
- **`check_name`**: verifies your Shiny app-package name is valid for CRAN, so we can set this to `FALSE` (unless you're planning on submitting to CRAN)
- **`roxygen2`**: is `TRUE` by default and adds the fields required to use `roxygen2` (which I won't cover here because we'll cover documentation in-depth in a future chapter).
```{r}
#| label: co_box_create_package_dot
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "r", fold = TRUE,
look = "default", hsize = "1.10", size = "1.05",
header = "Don't use `\".\"` with `create_package()`",
contents = "
When converting your existing Shiny app project into a Shiny app-package with `usethis::create_package()`, don't use `'.'` in the `path` argument:
\`\`\`r
usethis::create_package('.')
\`\`\`
This will return the following warning about creating nested projects, and ask if you want to proceed anyway:
`\`\`r
New project 'sap' is nested inside an existing project
'./', which is rarely a good idea. If this is unexpected,
the here package has a function,
`here::dr_here()` that reveals why './' is regarded as a
project.
Do you want to create anyway?
1: Yes
2: No way
3: Not now
`\`\`\
We can avoid this warning altogether by passing `getwd()` to the `path` argument, so I recommend cancelling the project creation:
\`\`\`r
Selection: 2
Error: Cancelling project creation.
\`\`\`
"
)
```
#### IDE arguments
- `rstudio`: adds the necessary **Build Tools** fields in the `.Rproj` file (leave as `TRUE`)
- `open`: can be set to `FALSE` because we don't need RStudio/Posit Workbench to open in a new session
```{r}
#| eval: false
#| code-fold: false
usethis::create_package(
path = getwd(),
fields = list(Package = 'sap',
Version = '0.0.0.9000',
Title = 'Shiny App-Packages',
Description = 'An R package with a collection of Shiny applications.',
"Authors@R" = NULL,
Author = utils::person(
given = "John",
family = "Smith",
email = "[email protected]",
role = c("aut", "cre")),
Maintainer = utils::person(
given = "John",
family = "Smith",
email = "[email protected]"),
License = "GPL-3"),
roxygen = TRUE,
check_name = FALSE,
rstudio = TRUE,
open = FALSE)
```
After running `usethis::create_package()` with the arguments above, the IDE will present us with a few prompts to confirm:
```{verbatim}
#| eval: false
#| code-fold: false
Overwrite pre-existing file 'DESCRIPTION'?
```
```{verbatim}
#| eval: false
#| code-fold: false
Overwrite pre-existing file 'sap.Rproj'?
```
The Shiny app-package structure is below:
``` sh
├── DESCRIPTION
├── NAMESPACE
├── R
│ ├── mod_scatter_display.R
│ ├── mod_var_input.R
│ └── utils.R
├── README.md
├── app.R
├── movies.RData
├── sap.Rproj
└── www
└── Shiny.png
3 directories, 10 files
```
The `DESCRIPTION` file (shown below) has a few additional fields (`Encoding`, `Roxygen`, and `RoxygenNote`) we didn't include when we converted `sap` above, but we will cover these in the upcoming chapters.
``` sh
Package: sap
Title: Shiny App-Packages
Version: 0.0.0.9000
Author: John Smith [aut, cre]
Maintainer: John Smith <[email protected]>
Description: An R package with a collection of Shiny applications.
License: GPL-3
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.3.2
```
```{r}
#| label: git_box_launch_03.3_create-package
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = "launch",
branch = "03.3_create-package")
```
## Recap {.unnumbered}
This chapter has covered the mandatory fields in the `DESCRIPTION` file and the R package configuration fields in `.Rproj`. We also covered creating and converting Shiny app projects using the `usethis::create_package()` function.
```{r}
#| label: co_box_recap
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "g",
fold = FALSE,
look = "default", hsize = "1.10", size = "1.05",
header = "Recap: Packages!",
contents = "
- **The `DESCRIPTION` file** ultimately controls whether you have a functional Shiny app-package.
- The mandatory fields are `Package`, `Version`, `License`, `Description`, `Title`, `Author`, and `Maintainer`.
- `usethis::create_package()` can be used to create a new R package and to convert an existing Shiny project into a Shiny app-package.
- The IDE reads Posit Workbench (`.Rproj`) files and determines R session settings at the project-level (i.e., working directory, workspace, history, code formatting, etc.)
- Package development settings can be accessed via **Project Options** > **Build Tools**.
"
)
```
In the next chapter, I'll cover how you can quickly **Load**, **Document**, and **Install** your package!
```{r}
#| label: git_contrib_box
#| echo: false
#| results: asis
#| eval: true
git_contrib_box()
```