forked from hadley/r-pkgs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntroduction.Rmd
231 lines (173 loc) · 15.6 KB
/
Introduction.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
231
# Introduction {#intro}
```{r, echo = FALSE}
source("common.R")
```
```{r, include = FALSE, eval = FALSE}
# takes a few seconds
x <- tools::CRAN_package_db()
nrow(x)
```
In R, the fundamental unit of shareable code is the package.
A package bundles together code, data, documentation, and tests, and is easy to share with others.
As of June 2022, there were over 18,000 packages available on the **C**omprehensive **R** **A**rchive **N**etwork, or CRAN, the public clearing house for R packages.
This huge variety of packages is one of the reasons that R is so successful: the chances are that someone has already solved a problem that you're working on, and you can benefit from their work by downloading their package.
If you're reading this book, you already know how to work with packages in the following ways:
- You install them from CRAN with `install.packages("x")`.
- You use them in R with `library("x")` or `library(x)`.
- You get help on them with `package?x` and `help(package = "x")`.
The goal of this book is to teach you how to develop packages so that you can write your own, not just use other people's.
Why write a package?
One compelling reason is that you have code that you want to share with others.
Bundling your code into a package makes it easy for other people to use it, because like you, they already know how to use packages.
If your code is in a package, any R user can easily download it, install it and learn how to use it.
But packages are useful even if you never share your code.
As Hilary Parker says in her [introduction to packages](https://hilaryparker.com/2014/04/29/writing-an-r-package-from-scratch/): "Seriously, it doesn't have to be about sharing your code (although that is an added benefit!). It is about saving yourself time." Organising code in a package makes your life easier because packages come with conventions.
For example, you put R code in `R/`, you put tests in `tests/` and you put data in `data/`.
These conventions are helpful because:
- They save time --- you don't need to think about the best way to organise a project, you can just follow a template.
- Standardised conventions lead to standardised tools --- if you buy into R's package conventions, you get many tools for free.
It's even possible to use packages to structure your data analyses (e.g., @marwick2018-tas or @marwick2018-peerj), although we won't delve deeply into that use case here.
## Philosophy {#intro-phil}
This book espouses our philosophy of package development: anything that can be automated, should be automated.
Do as little as possible by hand.
Do as much as possible with functions.
The goal is to spend your time thinking about what you want your package to do rather than thinking about the minutiae of package structure.
This philosophy is realized primarily through the devtools package, which is the public face for a suite of R functions that automate common development tasks.
The release of version 2.0.0 in October 2018 marked its internal restructuring into a set of more focused packages, with devtools becoming more of a meta-package.
The usethis package is the sub-package you are most likely to interact with directly; we explain the devtools-usethis relationship in @sec-setup-usage.
As always, the goal of devtools is to make package development as painless as possible.
It encapsulates the best practices developed by Hadley Wickham, initially from his years as a prolific solo developer.
More recently, he has assembled a team of developers at RStudio, who collectively look after hundreds of open source R packages, including those known as [the tidyverse](https://www.tidyverse.org).
The reach of this team allows us to explore the space of all possible mistakes at an extraordinary scale.
Fortunately, it also affords us the opportunity to reflect on both the successes and failures, in the company of expert and sympathetic colleagues.
We try to develop practices that make life more enjoyable for both the maintainer and users of a package.
The devtools meta-package is where these lessons are made concrete.
devtools works hand-in-hand with RStudio, which we believe is the best development environment for most R users.
The main alternative is [Emacs Speaks Statistics](https://ess.r-project.org/) (ESS), which is a rewarding environment if you're willing to put in the time to learn Emacs and customise it to your needs.
The history of ESS stretches back over 20 years (predating R!), but it's still actively developed and many of the workflows described in this book are also available there.
For those loyal to vim, we recommend the [Nvim-R plugin](https://github.com/jalvesaq/Nvim-R).
::: callout-tip
## RStudio
Throughout the book, we highlight specific ways that RStudio can expedite your package development workflow, in specially formatted sections like this.
:::
Together, devtools and RStudio insulate you from the low-level details of how packages are built.
As you start to develop more packages, we highly recommend that you learn more about those details.
The best resource for the official details of package development is always the official [writing R extensions](https://cran.r-project.org/doc/manuals/R-exts.html#Creating-R-packages) manual[^introduction-1].
However, this manual can be hard to understand if you're not already familiar with the basics of packages.
It's also exhaustive, covering every possible package component, rather than focusing on the most common and useful components, as this book does.
Writing R extensions is a useful resource once you've mastered the basics and want to learn what's going on under the hood.
[^introduction-1]: You might also enjoy the "quarto-ized" version at [https://rstudio.github.io/r-manuals/r-exts/](https://rstudio.github.io/r-manuals/r-exts/Function-and-variable-index.html).
## In this book {#intro-outline}
<!-- TODO: proof read this section -->
The first part of the book is all about giving you all the tools you need to start your package development journey and we highly recommend that you read it in order.
We begin in @sec-whole-game with a run through the complete development of a small package.
It's meant to paint the big picture and suggest a workflow, before we descend into the detailed treatment of the key components of an R package.
Then in @sec-setup you'll learn how to prepare your system for package development, and in @sec-package-structure-state you'll learn the basic structure of a package and how that varies across different states.
Next, in @sec-workflows101, we'll cover the core workflows that come up repeatedly for package developers.
Then the first section of the book in @sec-package-within with another case study, this time focusing on how you might convert a script to a package and discussing the challenges you'll face along the way.
The remainder of the book is design to be read as needed.
Pick and choose between the packages as you need them.
First we cover key package components: @sec-r discusses where your code lives and how to organize it, @sec-data shows you how to include data in your package, and @sec-misc covers a few less important files and directories that need to be discussed somewhere.
Next we'll dive into to the package metadata, starting with `DESCRIPTION` and `NAMESPACE` in @sec-metadata.
We'll then go deep into dependencies in @sec-dependencies, discussing when and how to depend on another package.
We'll finish off this part with a look at licensing in @sec-license.
To ensure your package works as designed (and continues to work as you make changes), it's essential to test your code, so the next three chapters cover the art and science of testing.
@sec-testing-basics gets you started with the basics of testing with the testthat package.
@sec-test-design teaches you how to design and organise tests in the most effective way.
Then we finish off our coverage of testing in @sec-testing-advanced which teaches you advanced skills to tackle the most challenging of cases.
If you want other people (including future-you!) to understand how to use the functions in your package, you'll need to document them.
@sec-man gets you started using roxygen to document the functions in your package.
Function documentation is only helpful if you know what function to look up, so next in @sec-vignettes we'll discuss vignettes, which help you document the package as a whole.
We'll finish up documentation with a discussion of other important markdown files like `README.md` and `NEWS.md` in @sec-man-markdown, and creating a package website with pkgdown in @sec-website.
The book concludes with a look at the release of your package to CRAN and the maintenance thereafter.
@sec-r-cmd-check dives into `R CMD check`, the most important tool for verifying your package is free from major defects.
You'll then learn how you can run `R CMD check` automatically every time you change your package in @sec-ci.
If you're planning on submitting your package to CRAN, @sec-release shows you the process and gives you our tips and tricks to maximize the chances of success.
We conclude with a discussion the post-release lifecycle in @sec-lifecycle.
This is a lot to learn, but don't feel overwhelmed.
Start with a minimal subset of useful features (e.g. just an `R/` directory!) and build up over time.
To paraphrase the Zen monk Shunryu Suzuki: "Each package is perfect the way it is --- and it can use a little improvement".
## What you won't learn {#you-wont-learn}
There are a few very important topics that you won't learn about in this book:
<!-- TODO: complete these comments -->
- Git and GitHub: mastering a version control system is vital to easily collaborate with others, and is useful even for solo work because it allows you to easily undo mistakes.
Learn from <https://happygitwithr.com/>.
- Compiled code: R code is designed for human efficiency, not computer efficiency, so it's useful to have a tool in your back pocket that allows you to write fast code.
Learn more in <https://adv-r.hadley.nz/rcpp.html>, or <https://cpp11.r-lib.org>.
- Markdown and RMarkdown.
## Acknowledgments {#intro-ack}
```{r eval = FALSE, include = FALSE}
# code generates fodder for the prose below
library(desc)
get_contributors <- function(pkg = "devtools") {
desc_get_authors(system.file("DESCRIPTION", package = pkg))
}
# using packages represented by hex stickers in 2019 usethis useR! talk
# team agreed that was the "right" set of packages
get_contributors("devtools")
get_contributors("usethis")
get_contributors("testthat")
get_contributors("pkgload")
get_contributors("rcmdcheck")
get_contributors("sessioninfo")
get_contributors("remotes")
get_contributors("revdepcheck")
get_contributors("pkgbuild")
get_contributors("roxygen2")
get_contributors("desc")
get_contributors("withr")
```
Since the first edition of R Packages was published, the packages supporting the workflows described here have undergone extensive development.
The original trio of devtools, roxygen2, and testthat has expanded to include the packages created by the "conscious uncoupling" of devtools, as described in @sec-setup-usage.
Most of these packages originate with Hadley Wickham (HW), because of their devtools roots.
There are many other significant contributors, many of whom now serve as maintainers:
- devtools: HW, [Winston Chang](https://github.com/wch), [Jim Hester](https://github.com/jimhester) (maintainer, \>= v1.13.5)
- usethis: HW, [Jennifer Bryan](https://github.com/jennybc) (maintainer \>= v1.5.0)
- roxygen2: HW (maintainer), [Peter Danenburg](https://github.com/klutometis), [Manuel Eugster](https://github.com/mjaeugster)
- testthat: HW (maintainer)
- desc: [Gábor Csárdi](https://github.com/gaborcsardi) (maintainer), [Kirill Müller](https://github.com/krlmlr), [Jim Hester](https://github.com/jimhester)
- pkgbuild: HW, [Jim Hester](https://github.com/jimhester) (maintainer)
- pkgload: HW, [Jim Hester](https://github.com/jimhester) (maintainer), [Winston Chang](https://github.com/wch)
- rcmdcheck: [Gábor Csárdi](https://github.com/gaborcsardi) (maintainer)
- remotes: HW, [Jim Hester](https://github.com/jimhester) (maintainer), [Gábor Csárdi](https://github.com/gaborcsardi), [Winston Chang](https://github.com/wch), [Martin Morgan](https://github.com/mtmorgan), [Dan Tenenbaum](https://github.com/dtenenba)
- revdepcheck: HW, [Gábor Csárdi](https://github.com/gaborcsardi) (maintainer)
- sessioninfo: HW, [Gábor Csárdi](https://github.com/gaborcsardi) (maintainer), [Winston Chang](https://github.com/wch), [Robert Flight](https://github.com/rmflight), [Kirill Müller](https://github.com/krlmlr), [Jim Hester](https://github.com/jimhester)
This book and the R package development community benefit tremendously from experts who smooth over specific pain points:
- [Kevin Ushey](https://github.com/kevinushey), [JJ Allaire](https://github.com/jjallaire), and [Dirk Eddelbuettel](http://dirk.eddelbuettel.com) tirelessly answered all sorts of C, C++, and Rcpp questions.
- [Craig Citro](https://github.com/craigcitro) wrote much of the initial code to facilitate using Travis-CI with R packages.
- [Jeroen Ooms](https://github.com/jeroen) also helps to maintain R community infrastructure, such as the current R support for Travis-CI (along with Jim Hester), and the Windows toolchain.
*TODO: revisit rest of this section when 2nd edition nears completion. Currently applies to and worded for 1st edition.*
Often the only way I learn how to do it the right way is by doing it the wrong way first.
For suffering through many package development errors, I'd like to thank all the CRAN maintainers, especially Brian Ripley, Uwe Ligges and Kurt Hornik.
This book was [written and revised in the open](https://github.com/hadley/r-pkgs/) and it is truly a community effort: many people read drafts, fix typos, suggest improvements, and contribute content.
Without those contributors, the book wouldn't be nearly as good as it is, and we are deeply grateful for their help.
A special thanks goes to Peter Li, who read the book from cover-to-cover and provided many fixes.
I also deeply appreciate the time the reviewers ([Duncan Murdoch](http://www.stats.uwo.ca/faculty/murdoch/), [Karthik Ram](http://karthik.io), [Vitalie Spinu](http://vitalie.spinu.info) and [Ramnath Vaidyanathan](https://ramnathv.github.io)) spent reading the book and giving me thorough feedback.
```{r, results = "asis", echo = FALSE, eval = TRUE}
# git --no-pager shortlog -ns > contribs.txt
contribs <- read.delim("data/contribs.txt", header = FALSE,
stringsAsFactors = FALSE)[-1, ]
names(contribs) <- c("n", "name")
contribs <- contribs[order(contribs$name), ]
contribs$uname <- ifelse(!grepl(" ", contribs$name),
paste0("`@", contribs$name,"`"), contribs$name)
cat("Thanks go to all contributors who submitted improvements via github (in alphabetical order): ")
cat(paste0(contribs$uname, collapse = ", "))
cat(".\n")
```
## Conventions {#intro-conventions}
Throughout this book, we write `fun()` to refer to functions, `var` to refer to variables and function arguments, and `path/` for paths.
Larger code blocks intermingle input and output.
Output is commented so that if you have an electronic version of the book, e.g., <https://r-pkgs.org>, you can easily copy and paste examples into R.
Output comments look like `#>` to distinguish them from regular comments.
## Colophon {#intro-colophon}
This book was authored using [Quarto](https://quarto.org) inside [RStudio](https://www.rstudio.com/products/rstudio/).
The [website](https://r-pkgs.org) is hosted with [Netlify](https://www.netlify.com), and automatically updated after every commit by GitHub actions.
The complete source is available from [GitHub](https://github.com/hadley/r-pkgs).
This version of the book was built with:
```{r}
library(devtools)
library(roxygen2)
library(testthat)
devtools::session_info()
```