Include functions from package in development into examples for functions of the same package

24 views Asked by At

When developing an R package, how can I rely on functions that are part of that package in examples for other functions of that package?

Suppose I have a function generating sample data inside my package named testdata()

In another function named modify_data() I want to modify sample data generated with testdata()

How can I refer to the function testdata() in the @example of the roxygen2 skeleton? I tried the following:

#' @examples
#' sample_data <- testdata(some_parameters)
#' sample_data <- modify_data(sample_data)

or

#' @examples
#' sample_data <- mypackagename::testdata(some_parameters)
#' sample_data <- modify_data(sample_data)

But when R CMD checking the package contents I always get an error for the examples saying:

Error: could not find function "testdata"

or

Error: 'testdata' is not an exported object from 'namespace:mypackagename'

Is it possible to rely on other package functions inside the examples for another function? I feel like it should work somehow, but cannot get behind the correct way to do so...

1

There are 1 answers

0
MrFlick On

The examples on a help page should allow the user to copy/paste the code and have it run successfully to demonstrate the correct use of a package (or run when calling example(modify_data)). That means that all the functions used in the example need to be exported from the package you are creating. It appears you are using roxygen so you can mark the function you want to use as exported with

@export
testdata <- function(...) {
  ...
}

Though it might not make sense to have a function called testdata exported from your package if that's not really part of your API. You can include sample datasets in your package or define data in the example itself like they do in the ?lm help page.