Creating an R package

a not too comprehensive step by step guide

Posted by daniel on Tue, Apr 11, 2017
In R
Tags tutorial, rstats, development, basics

R packages – why it is useful to create one…

(non-exhaustive, personally biased [of course] list):

  1. to easily share your code in a “out of the box” format
  2. to force yourself to abstract the ideas of your analysis
  3. to force yourself to document
  4. to learn to be a better (i.e. less trial-and-errorish) coder by writing your analysis in function-like statements

How?

  1. create folder with the name of the package: MyPackage [or use devtools::create("MyPackage")to automatically add a bare-bones description file in an empty folder]
  2. create in this directory another directory called R
  3. put the R-code files into this directory
  4. within the MyPackage folder create a file named DESCRIPTION with the following (or similar) content:

    Package: MyPackage
    Version: 0.1
    Date: 2017-04-11
    Title: My very own package
    Description: An R package for something interesting and/or important. etc.
    Author:
    Me <me@mymail.eu>,
    Maintainer: Me again <me@mymail.eu>
    License: GPL-3
    
  5. [OPTIONAL when Roxygen2is used, see next point]
    Create a NAMESPACE file with the following, minimal content:

    # Export all names
    exportPattern(".")
    
  6. Create the documentation;
    first create in the a subdirectory called man in the package directory. In this folder *.Rd* files for each function are stored in a LaTeX-like format. Since this can be difficult or you might forget to create some files, there is the Roxygen2 package that takes care of creating the *.Rd* files and that forces you the write the documentation of the code directly within the R-code files; besides Roxygen2 creates the NAMESPACE automatically

  7. each function argument gets is documented like this:
    #' @param argument_name description of the argument

  8. the return value of the function is documented using:
    #' @return something important for A2

  9. examples are documented with:
    #' @examples x <- 1

  10. The @export line at the end tells Roxygen2 to add the function to the NAMESPACE file:
    #' @export myfunction

  11. Finally create the documentation using devtools::document() [in case you are within R and within the package directory] [emacs ess shortcut C-c C-w d]

  12. build the package: devtools::build()

  13. install the package: devtools::install() [emacs ess shortcut C-c C-w i]

  14. and check: devtools::check() [emacs ess shortcut C-c C-w c]

other things

to create the pdf manual run: R CMD Rd2pdf MyPackage

you can also use the package.skeleton(name="PACKAGENAME", code_files="CODEFILE.R") command to create the necessary folders/files/etc. for the package. Building and installing is done as described above.

Sources

other probably interesting resources