Slide 1

Slide 1 text

1 WRITING R PACKAGES
 PART I Jeff Goldsmith, PhD Department of Biostatistics

Slide 2

Slide 2 text

2 When to write packages “If you have more than two functions, write a package” - almost everyone, basically

Slide 3

Slide 3 text

3 In particular, why not just write a lot of functions in scripts or R Markdown code chunks? • Documentation reminds you what functions do, what inputs are, and what outputs are • Encapsulates code in standard, easy-to-share format • Checks / tests ensure things are self contained and work as expected Why to write packages

Slide 4

Slide 4 text

4 Why to write packages “I wish I could go back in time and create the package the first moment I thought about it, and then use all the saved time to watch cat videos because that really would have been more productive.” “It is about saving yourself time.” - Hilary Parker, “Writing an R Package from Scratch”

Slide 5

Slide 5 text

4 Why to write packages “I wish I could go back in time and create the package the first moment I thought about it, and then use all the saved time to watch cat videos because that really would have been more productive.” “It is about saving yourself time.” - Hilary Parker, “Writing an R Package from Scratch”

Slide 6

Slide 6 text

5 • Collection of related functions, with helpful documentation, written to stand alone • Can also include data, vignettes, non-R code (e.g. C++), tests, … What is a package?

Slide 7

Slide 7 text

6 • Metadata / overview • Help pages • Dependencies • Code Parts of a bare-bones package You can edit the DESCRIPTION and the R code yourself, but you should use other tools to generate the help pages and the NAMESPACE

Slide 8

Slide 8 text

7 With apologies to Hilary … • Step 0: whatever work you did to get to 2+ functions. • Step 1: create package skeleton with devtools::create() • Step 2: add your functions to /R/ • Step 3: add documentation using roxygen comments • Step 4: iterate Can also add a README and put on GitHub. How to write a package

Slide 9

Slide 9 text

8 • Start small: – Write small functions that do one thing well and interact easily – Avoid unneeded complexity – When you have a couple of functions, put them in a package – Build complexity as needed • Clarity is better than cleverness How to write a package

Slide 10

Slide 10 text

9 How to write a package Jeff Leek’s Guide to Writing R Packages