Assume that I have two functions f
and g
and in my roxygen2
documentation I want that the @examples
of g
extend the examples of f
.
If I write them by hand, it would look like this:
#' Adds One to Its Argument
#'
#' @param x Number to which one should be added.
#'
#' @return `x` plus one.
#' @export
#'
#' @examples
#' x <- 2
#' (y <- f(x))
f <- function(x) {
x + 1
}
#' Adds Two to Its Argument
#'
#' @param x Number to which two should be added.
#'
#' @return `x` plus two.
#' @export
#'
#' @examples
#' x <- 2
#' (y <- f(x))
#' g(y)
g <- function(x) {
x + 2
}
You see that the @examples
section of g
is the same as the one of f
amended by an additional line.
Originally I thought I could simply use @inherit f examples
and amend the example but this does not work (as soon as you add a separate @examples
tag it ignores the inherited example).
After having read the vignette on re-using docs I thought that the way to go is to write a function generate_example
, say, which creates the example scaffold and call it then from within @examples
generate_example <- function() {
"x <- 2
(y <- f(x))"
}
#' [...]
#' @examples
#' `r generate_example()`
f <- function(x) {
x + 1
}
#' [...]
#' @examples
#' `r generate_example()`
#' g(y)
g <- function(x) {
x + 2
}
But this places a literal `r generate_example()`
in my docs (and even if it worked, it would be quite cumbersome to write R code as strings).
What is thus the canonical way of defining an example scaffold / template to be used in several places?
Ahh, one way would be to place the example code n a separate file (example.R
say) and then use the @example path/to/example.R
tag and amend the example with @examples
:
#' Adds One to Its Argument
#'
#' @param x Number to which one should be added.
#'
#' @return `x` plus one.
#' @export
#'
#' @example R/example.R
f <- function(x) {
x + 1
}
#' Adds Two to Its Argument
#'
#' @param x Number to which two should be added.
#'
#' @return `x` plus two.
#' @export
#'
#' @example R/example.R
#' @examples
#' g(y)
g <- function(x) {
x + 2
}