Upgrade to Pro — share decks privately, control downloads, hide ads and more …

P8105: Writing R Packages I

Jeff Goldsmith
November 26, 2017

P8105: Writing R Packages I

Jeff Goldsmith

November 26, 2017
Tweet

More Decks by Jeff Goldsmith

Other Decks in Education

Transcript

  1. 1
    WRITING R PACKAGES

    PART I
    Jeff Goldsmith, PhD
    Department of Biostatistics

    View Slide

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

    View Slide

  3. 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

    View Slide

  4. 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”

    View Slide

  5. 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”

    View Slide

  6. 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?

    View Slide

  7. 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

    View Slide

  8. 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

    View Slide

  9. 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

    View Slide

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

    View Slide