My workflow in working with functions in a package

RSE
Rpkg

Structure them, write them, test them, document them.

Author

Chi Zhang

Published

October 8, 2023

Ongoing notes

Some of the content are being added as I go.

Functions make up the whole R package, except for data-only packages. The workflow should help me navigate the process.

A short example borrowed from GSWEP4R workshop is documented here, function code and test code

Structure

Write

What to return?

Put the arguments in a list named result, then attach other outputs to result.

result <- list(arg1 = arg1, arg2 = arg2)

Afterwards, set class attribute to something meaningful, for example,

result <- structure(result, class = 'SimulationResult')

This allows us to implement generics.

Generics

Common generics

  • print
  • summary
  • plot
print.classname <- function(x, ...){
  # x is an object of `classname`
  # it should be a list, and have class attribute `classname`
}

Test

Tests for functions and generic functions seem to be the same as before. Need to go back to the function and add error messages.

Document

The way to document generic functions is exactly the same as any other function.

#' Print method
#'
#' @description
#' Generic function to print a `SimulationResult` object
#'
#' @param x a \code{SimulationResult} object to print
#' @param ... further arguments to pass from other methods
#'
#' @return something printed
#' @export
#'
#' @examples
#' simd <- fsim(n1 = 10, n2 = 10, mean1 = 0, mean2 = 5, sd1 = 1, sd2 = 1)
#' print(simd)