forked from RVerse-Tutorials/RWorkflow-NWFSC-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
week6-more-packages.Rmd
231 lines (161 loc) · 10.9 KB
/
week6-more-packages.Rmd
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
---
title: "Week 6: Advanced package topics"
output:
html_document:
toc: true
include:
after_body: footer.html
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
set.seed(1234)
```
```{r echo=FALSE, message=FALSE, warning=FALSE}
library(kableExtra)
dt <- data.frame("Compartmentalized", "Documented", "Extendible", "Reproducible", "Robust")
kable(dt, col.names=NULL) %>%
kable_styling(full_width = TRUE) %>%
row_spec(1, bold = FALSE, color = "white", background = "blue") %>%
column_spec(column = 1:5, width = "20%")
```
This week I will cover more advanced topics regarding R packages:
* How to use the "check" feature to find problems in your package.
* How to write a vignette for your package.
* How to write print and plot functions for your objects.
* Using pkgdown to make a website for your package.
If/when you want to go into R packaging in more depth, work through the material from this [R package workshop material](https://combine-australia.github.io/r-pkg-dev/). You've seen much of this material so it should be somewhat familiar. See also Hadley Wickham's book [R Packages](http://r-pkgs.had.co.nz/).
The repository that I used to demo these features is here:
https://github.com/eeholmes/MyNewPackage
## Checking your package
Just use the RStudio Check in the Build tab. You'll have many issues (most likely). Plug away at each one until you pass with no errors or warnings. Don't ignore Notes either. They are sometimes more serious than the errors and warnings.
If R asks you to update packages, and then proceeds to fail at installation because of a warning that a package was built under a later R version than you have on your computer, use
```
Sys.setenv(R_REMOTES_NO_ERRORS_FROM_WARNINGS=TRUE)
```
## Creating print and plot methods for your objects
### Make your output an object
```
littleforecast <- function(data, nyears=10){
fit <- forecast::auto.arima(data)
fc <- forecast::forecast(fit, h = nyears)
ggplot2::autoplot(fc)
class(fit) <- c("foo", class(fit))
return(fit)
}
```
### print method
```
#' Prints foo object
#'
#' prints a foo object returned from littlefunction().
#'
#' @param x foo object
#' @param ... Not used
#' @method print foo
#' @export
print.foo <- function(x, ...) {
cat("Hello there")
}
```
### plot method
```
#' Plots foo object
#'
#' Plots foo object.
#'
#' @param x An foo object.
#' @param ... Not used.
#' @method plot foo
#' @export
plot.foo <- function(x, ...) {
plot(1:10)
}
```
Note, `plot()` is part of the graphics package so you need to add that to Imports in your DESCRIPTION file. Our Imports line is now:
```
Imports: forecast, graphics
```
### Add your methods to your namespace
```
S3method(print,foo)
S3method(plot,foo)
```
### Example
Install and restart MyNewPackage.
```
fit=littleforecast(WWW2)
fit
plot(fit)
```
## Writing a vignette
Doing this in RStudio is easy. See [rmarkdown vignette chapter](https://bookdown.org/yihui/rmarkdown-cookbook/package-vignette.html) and [Hadley's vignette chapter](http://r-pkgs.had.co.nz/vignettes.html) for more info.
### Making the vignette
Manually
* Make a vignettes folder at the base level (same level as the R folder)
* Create a new vignette file from a template. RStudio > File > New > R Markdown > From Template > Vignette
* Save in vignettes folder
* Change the title in the 2 places in the yaml at the top. 'yaml' is between the `---` fences.
* Add the following 2 lines to your DESCRIPTION file:
```
Suggests: knitr, rmarkdown
VignetteBuilder: knitr
```
Or use a helper function:
```
devtools::use_vignette("my-vignette")
```
or
```
usethis::use_vignette("MyNewPackage")
```
### Testing your vignette
Open your vignette file and click the Knit button.
### Getting your vignette to show up
Once you have your vignettes in the `vignettes` folder, you'l like to be able to build them and have them appear when you type `browseVignettes("MyNewPackage")`. This will not work. In fact, RStudio seems to actively hinders this workflow.
Vignettes can take a long time to build and by default when R builds a package from source (which is what Install and Restart on the build tab does), it does not re-make your vignettes. You can make RStudio re-make your vignettes in the `vignettes` folder (if the Rmd file changes) using Tools > Project Options > Build Tools > Generate documentation with Roxygen > Configure and clicking the vignettes check-box. But this will not get your vignettes loaded when you click Install and Restart on the Build tab (`browseVignettes()` still won't work).
So how does R know about your vignettes when it is building from source (i.e. from Install and Restart in the Build tab in RStudio)? It needs the vignette files (.Rmd, .R and .html) in the `inst/doc` folder. How do you get them there? You have to put them there.
That's easy. I'll just put them there whenever I change or add vignettes. Unfortunately, the default RStudio default behavior is to delete the whole `inst/doc` folder whenever you click Check (package) in the Build tab. It's happening because the default is to use `devtools::check()` and there is no way to set `devtools::check(vignettes=FALSE)`. To stop RStudio from deleting `inst/doc` on package checking, uncheck the `use devtools package functions if available` box. You may also want to add `--no-manual` to the R CMD Check options box since that is the default for `devtools::check()`.
This is my vignette workflow:
* Create the `vignette` folder and add vignette Rmds to it using the R Markdown vignette template in RStudio.
* Create the `inst` folder in my package at the base level (same level as the R folder).
* Edit my vignette Rmd and use the Knit button to preview.
* When I am done, run the following code to update the vignette files and copy to the `inst/doc` folder.
```
tools::buildVignettes(dir = ".", tangle=TRUE)
dir.create("inst/doc")
file.copy(dir("vignettes", full.names=TRUE), "inst/doc", overwrite=TRUE)
```
Once your vignette files are in `inst/doc`, Install and Restart button will add the vignettes to your package and `install_github()` will have them too.
**Careful, RStudio `Check` in the Build tab will delete the `inst/doc` folder and not recreate it.** So always check that `inst/doc` not been trashed and **uncheck** the `use devtools package functions` checkbox on the Build > More > Configure Build Tools... window. You will most likely also want to add `--no-manual` to the `R CMD check additional options` box.
## **pkgdown**
[pkgdown](https://pkgdown.r-lib.org/articles/pkgdown.html) makes it easy to make nice webpages for your packages.
## Depends versus Imports
**@Depends** These packages that will be loaded when your package is loaded. So if you have **gplot2** in @Depends, like above, then the user automatically can use **ggplot2** functions without issuing the command `library(ggplot2)`.
**@Imports** Are required for the package functions, but the user will not have access to the functions without calling `library(...)`. In your package, you will use `::` to access the functions from the packages on the @Imports line. *Most of your package dependencies will be here.*
To limit the number of headaches that users face when trying to install your package, use as few packages on your @Depends and @Imports lines in DESCRIPTION file as possible. If your package does not need the package to work, then put the package on @Suggests.
I have R packages that are mainly for my personal use. I use the package to make sure I have access to the various packages that I'll be using. So for example, if I am doing work on my sardine papers, I have set of packages that I use. When I issue the command `library(SardineForecast)` a bunch of packages are loaded. This makes it handy for me, but all those dependencies makes it a huge hassle to install the package from GitHub for my collaborators (and even a hassle for me to install from GitHub). Huge Hassle. Invariable one of the 15 packages that I need will itself have a dependency that won't load and then I have to debug that. If I need collaborators, who are on different operating systems and various versions of R to install it, it's a suffer-fest.
For my MARSS package, I have only 3 non-base dependencies in the @Imports line and nothing on the @Depends line besides R. The imports are KFAS, mvtnorm, and nlme. Then on the @Suggests line, I have a bunch of packages that are used in the vignettes. MARSS is easy to install from GitHub (though it is also hosted on CRAN).
**What should you put on your Depends and Imports lines?**
First off, when you are starting, don't worry too much about this. Just add packages that are needed as you work on your functions.
* ALWAYS use `::` to use functions from other packages in your package functions. Seriously. You will save yourself so many headaches down the road by being able to search for `xyzpackage::` to find all that packages functions. Why? Trust me, one day you will want to swap out packages or remove dependencies. Note, this can be a hassle with functions like `ggplot()` which use functions within their calls and you have to use `::` everywhere. Like so
```{r eval=FALSE}
ggplot2::ggplot(df) +
ggplot2::geom_point(ggplot2::aes(gp, y))
```
Arg. Another example is say a GAM call:
```{r eval=FALSE}
mgcv::gam(a ~ mgcv::s(b), data=df)
```
But this is just for your package functions. In your scripts, you'd probably use a `library()` call.
* Never ever use `library()` in a function! Use `xyzfunction::function`. Sure use `library()` in your scripts, but never in a package function. When you add a function from a new package to your function, add those packages to @Depends or @Imports in your DESCRIPTION file as you go along.
* Every so often check that you don't have packages on @Depends and @Imports that you don't use. Just do a Edit > Find in Files... search for `xyzpackage::` to find out if you are still using `xyzpackage`.
* How do you know if you forgot a dependency or forgot a `::` somewhere? Two ways:
1. Do Session > Restart R to close all your loaded packages. Then load your package with `library(yourpackagename)` and try your functions. Things will fail if you have a package in @Imports but forgot a `::` somewhere.
2. From the Build tab, use More > Check Package. That should show package dependency errors (plus a whole slew of other problems for you to work through).
## Styling your code
You should stick with a uniform style guide to make your code easier to follow. I use the tidyverse style guide with the [**styler** R package](https://www.tidyverse.org/blog/2017/12/styler-1.0.0/). **styler** has an RStudio Addin which does all the work of styling my code for me. Install the package, restart RStudio, and then go to Tools > Addins > Browse Addins. Scroll down to styler, and select the file(s), you want to style.
## Byte Compile
Adding this line to your DESCRIPTION file can really speed up your code. This is one of the advantages of putting your functions in a package. It can actually make your functions faster.
```
ByteCompile: TRUE
```