11 Apr 2017
Creating an R package
…a not too comprehensive step by step guide…
R packages – why it is useful to create one…
(non-exhaustive, personally biased [of course] list):
- to easily share your code in a "out of the box" format
- to force yourself to abstract the ideas of your analysis
- to force yourself to document
- to learn to be a better (i.e. less trial-and-errorish) coder by writing your analysis in function-like statements
How?
- 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/] - create in this directory another directory called
R - put the R-code files into this directory
- within the
MyPackagefolder create a file namedDESCRIPTIONwith 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
- [/OPTIONAL/ when
Roxygen2=is used, see next point]\\ Create a =NAMESPACEfile with the following, minimal content:
# Export all names exportPattern(".")
- Create the documentation;
first create in the a subdirectory calledmanin 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; besidesRoxygen2creates theNAMESPACEautomatically - each function argument gets is documented like this:
#' @param argument_name description of the argument - the return value of the function is documented using:
#' @return something important for A2 - examples are documented with:
#' @examples x <- 1 - The @export line at the end tells
Roxygen2to add the function to theNAMESPACEfile:
#' @export myfunction - Finally create the documentation using
devtools::document()[in case you are withinRand within the package directory] [emacs ess shortcut =C-c C-w d=] - build the package:
devtools::build() - install the package:
devtools::install()[emacs ess shortcut =C-c C-w i=] - 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", codefiles="CODEFILE.R")= command
to create the necessary folders/files/etc. for the package. Building and
installing is done as described above.