9

When documenting a function with roxygen2 it is possible to place examples in a separate file.

See here: http://r-pkgs.had.co.nz/man.html "Instead of including examples directly in the documentation, you can put them in separate files and use @example path/relative/to/packge/root to insert them into the documentation."

and here: http://roxygen.org/roxygen2-manual.pdf

e.g.

#' Add together two numbers.
#' 
#' @param x A number.
#' @param y A number.
#' @return The sum of \code{x} and \code{y}.
#' @example /path/to/example/add.R
add <- function(x, y) {
  x + y
}

My question is: what path should be used to store the example R files?

waferthin
  • 1,582
  • 1
  • 16
  • 27
  • I think /inst/ moves to / when installing the package? I guess this won't matter though if the documentation is already built? – waferthin Sep 30 '14 at 10:11
  • 1
    Yes `inst/examples` should move to `examples` and I would think you could then reference `/examples` in your documentation. – jdharrison Sep 30 '14 at 10:12
  • OK inst/examples works well. I can reference /inst/examples/file.R in the source code, then create documentation with devtools::document(). /inst/examples moves to /examples, but I think this is irrelevant as the documentation is already built... – waferthin Sep 30 '14 at 10:24
  • I can't decide if this is a good idea or not. It makes it a bit easier to run your examples, but isn't the whole point of roxygen that you keep the documentation right next to where the function is defined? – Richie Cotton Sep 30 '14 at 11:11

1 Answers1

6

The appropriate location for examples used in your roxygen is:

inst/examples/

The roxygen line then should be:

#' @example inst/examples/add.R

Is this good practice? I think it is, since:

  • It makes it easier to run, modify and test the examples whilst developing
  • It makes it possible (in principle, at least) to re-use the examples in different places in the documentation, e.g. in the vignette
Andrie
  • 176,377
  • 47
  • 447
  • 496
  • 1
    I find it useful when I have many lines for the examples with indentation that I want to preserve. Most of the time I still use @examples though. – waferthin Sep 30 '14 at 14:38