Let’s build a package for R! Here is a nice book to explain what we’re going to do!
(I use this single Emacs org-mode file to do everything! But you can just work on the separate files as well)
We use devtools and usethis for the setup, roxygen2 for the documentation,
If you haven’t installed them yet, run the following:
install.packages(c("devtools", "usethis", "roxygen2"))
library(devtools)
library(usethis)
Run the below code to set up the author and package info metadata.
options(
usethis.full_name = "Ilja Kocken",
usethis.description = list(
`Authors@R` = 'person("Ilja", "Kocken", email = "i.j.kocken@uu.nl", role = c("aut", "cre"),
comment = c(ORCID = "0000-0003-2196-8718"))',
Version = "0.0.0.9000")
)
This is an example function.
Here we use :tangle
to export the file to R/utils.R
, but you can of course also create a new file directly in the R subdirectory.
#' Moving average
#'
#' @importFrom stats filter
#' @param x A vector to create the moving average for.
#' @param n The number of samples to create the moving average for.
#' @param sides the
#' @export
ma <- function(x, n = 5, sides = 2) {
filter(x, rep(1/n, n), sides = sides)
}
Here’s the basic syntax for roxygen function documentation directly next to the function definition. This is one of the examples from the documentation workflow section of the r-pkgs book.
#' Add together two numbers
#'
#' @param x A number.
#' @param y A number.
#' @return The sum of \code{x} and \code{y}.
#' @examples
#' add(1, 1)
#' add(10, 1)
add <- function(x, y) {
x + y
}
There’s often a zzz file to put several options in, like a startup message.
.onAttach <- function(libname, pkgname) {
packageStartupMessage("Welcome to ‘clumpedr’")
}
Now we run below options one by one to interactively set up the package skeleton!
Be sure to answer the questions and to update the new files as they are created.
create_package("~/SurfDrive/PhD/programming/rpackagefromorg/") # example path to your package!
use_gpl3_license()
use_roxygen_md()
use_package_doc()
use_vignette("my-vignette")
use_testthat() # write tests for your functions!
use_test("add")
use_pipe()
use_tibble()
document()
Raw data that needs to be accessible can be stored in inst/
. This is best if you want to demonstrate how to load the data in your vignette.
If you want the data available as a dataset, loadable with data(nameofdata)
, put it in data/
as a .rds
(R data structure) file.
In this case it’s probably a good idea to include the source code + raw data in data-raw/
.
See this section on how to document data.
tree
. ├── DESCRIPTION ├── LICENSE.md ├── man │ ├── add.Rd │ ├── ma.Rd │ ├── pipe.Rd │ └── rpackagefromorg-package.Rd ├── NAMESPACE ├── R │ ├── add.R │ ├── rpackagefromorg-package.R │ ├── utils-pipe.R │ ├── utils.R │ ├── utils.Rmd │ └── zzz.R ├── README.org ├── tests │ ├── testthat │ │ └── test-add.R │ └── testthat.R └── vignettes └── my-vignette.Rmd 5 directories, 17 files