Getting Started

Start by creating a directory with the appropriate name: it should contain only letters and numbers. Inside this create a folder called R for your code.

mkdir testpkg
cd testpkg
mkdir R

Write your code in files with an .R extension, and put them in the R folder. You can split the functions between files however you wish, but try to think about how you can make it easy for someone else to read your code.

Loading A Package

Once you have some code in your R folder, move to your package’s root directory, and run


(You may need to install the devtools package.)


You can document a function using Roxygen notation. Comments beginning #' (hash followed by apostrophe) will be automatically processed by Roxygen into R style documentation.


(You need the roxygen2 package installed.)

#' Squares numbers
#' @param x numeric vector to be squared
#' @return a numeric vector of the same length as \code{x}
#' @details some more information about this function
#' @export sq
sq = function(x) x^2

If you load your package again using devtools::load_all(), then you should be able to see your documentation using ? as normal.

The @export command ensures that your function is visible at the command line when your package is loaded (so when a used types its name, they will see the function). This is generally recommended.


Like documentation, testing is boring but important. You want to make sure that if you change some feature of your code, everything keeps working. It’s advantageous to be systematic about this: you can build up a suite of checks which will reassure you the functions do what their supposed to.

To get started, run


This creates a folder tests/testthat/ in your root directory. Put your tests as R script files insider this folder. Tests take the form of a call to test_that():

test_that("A description of the test I'm doing", {
  # put some tests in here
  expect_equal(sq(2), 4)

Once you have a few tests, you can run them using


Any failures should be displayed to you.

Relevant functions: expect_equal(), expect_identical(), expect_warning(), expect_error(), expect_message(), expect_null()


If your test fails, it may not be totally obvious to you why! See the debugging page for some approaches to this.


With a partner, create a package for discrete Markov chain methods.

First define a class for Markov chain objects, which should consist of:

Make sure your package includes:

See also:

The vignettes page.