Documenting functions with roxygen2
Keep reference manuals, NAMESPACE exports, and runnable examples aligned with your code
The problem: documentation that drifts
In analysis scripts and informal collections of helper functions, documentation is rarely more than a comment header or a separate specification document. As analysis requirements evolve, arguments are added, default values change, and return structures are refactored. That separate document, stored in a shared directory or wiki, rarely keeps pace.
When a team moves those functions into an R package, the consequence becomes immediate: typing ?format_n_pct in the console prints No documentation for ‘format_n_pct’ in specified packages and libraries. R stores package help pages as .Rd files in man/. For a documented function, a generated page commonly contains \name, \alias, \title, \description, \usage, \arguments, \value, and \examples. These sections are not all mandatory; R CMD check separately checks exported functions for missing documentation and compares documented arguments with the function usage:
\name{format_n_pct}
\alias{format_n_pct}
\title{Format a count and percentage}
\usage{
format_n_pct(n, denom, digits = 1)
}
\arguments{
\item{n}{Numeric vector of counts.}
\item{denom}{Denominator: a single positive finite number.}
\item{digits}{Non-negative whole number of decimal places.}
}
\value{
A character vector the same length as \code{n}.
}
\description{
Formats counts and percentages for summary tables.
}
Hand-written Rd files create a dual-maintenance problem: A change to a function’s arguments requires the corresponding usage and argument documentation to stay aligned. A change to what the package exports also requires the NAMESPACE directives to stay aligned. R CMD check reports undocumented arguments, and an unexported function cannot be called by users with the pkg::fun() syntax.
In regulated work, stale help pages make review harder. The {riskmetric} assessments assess whether exported values have help entries and whether function documentation contains example or usage fields (see validation-ready R packages). Those presence checks do not show that the examples run or that the help text matches the implementation.
The web-repo way: generated from source
One way to reduce documentation drift is to keep documentation beside the code it describes.
In JavaScript and TypeScript repositories, developers place JSDoc comments (/** ... */) directly above function definitions. Tags such as @param, @returns, and @example declare metadata that tools like TypeDoc compile into reference documentation. In Python, PEP 257 standardises docstrings embedded directly inside function bodies. Tools such as Sphinx’s autodoc extract these docstrings to build API documentation sites. Python’s doctest module goes further: it parses interactive sessions in docstrings and executes them, verifying that code runs and matches recorded output.
Both workflows keep human-written documentation close to the code and can generate reference pages from it. Verification is a separate step: Python’s doctest can execute examples and compare output, while TypeDoc turns comments into reference documentation.
In R, {roxygen2} implements this workflow. You write structured comment blocks directly above function definitions in R/, and devtools::document() compiles them into man/*.Rd files and NAMESPACE export directives. One distinction from Python’s doctest is that R CMD check executes examples and halts on unhandled errors, but it does not compare console print output to expected text unless the package ships a reference file, tests/Examples/<pkg>-Ex.Rout.save (Writing R Extensions, §1.3.1).
The R way: roxygen2 blocks and the compilation loop
Anatomy of a roxygen block
A roxygen block sits immediately before a function definition. Each line begins with the comment prefix #'. The block uses specific tags to populate the corresponding sections of the generated Rd file:
check_digits <- function(digits) {
if (!is.numeric(digits) || length(digits) != 1L ||
!is.finite(digits) || digits < 0 || digits != floor(digits)) {
stop("`digits` must be a single non-negative whole number.", call. = FALSE)
}
invisible(TRUE)
}
#' Format a count and percentage
#'
#' Formats `n` out of `denom` as `"n (pct%)"`, the way counts appear
#' in a summary table.
#'
#' @param n Numeric vector of counts.
#' @param denom Denominator: a single positive finite number.
#' @param digits Non-negative whole number of decimal places.
#' @returns A character vector the same length as `n`.
#' @family formatting helpers
#' @export
#' @examples
#' format_n_pct(c(12, 30), denom = 86)
#' format_n_pct(5, denom = 86, digits = 0)
format_n_pct <- function(n, denom, digits = 1) {
if (!is.numeric(denom) || length(denom) != 1L ||
!is.finite(denom) || denom <= 0) {
stop("`denom` must be a single positive finite number.", call. = FALSE)
}
check_digits(digits)
pct <- formatC(100 * n / denom, format = "f", digits = digits)
paste0(n, " (", pct, "%)")
}
format_n_pct(c(12, 30), denom = 86)The roxygen parser maps this structure to Rd elements:
- Title: The first sentence or paragraph becomes
\title{...}. - Description: The second paragraph becomes
\description{...}. If you omit the second paragraph, roxygen2 reuses the title as the description. @param name Description: Defines an argument in the\arguments{}section. Roxygen2 inspectsformals(fun)to generate the\usage{}line automatically, including default arguments.@returns(or@return): Documents the return object type and structure in\value{...}. R Packages (2e) uses@returns.@export: Directs roxygen2 to writeexport(format_n_pct)toNAMESPACE. Functions without@exportremain internal to the package.@examples: Contains executable R code demonstrating typical usage.
What document() writes
To compile roxygen comments into package documentation, run devtools::document(), which delegates to roxygen2::roxygenise():
devtools::document()This command parses all files in R/ and updates two build artifacts:
man/format_n_pct.Rd: The generated manual file:
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/format.R
\name{format_n_pct}
\alias{format_n_pct}
\title{Format a count and percentage}
\usage{
format_n_pct(n, denom, digits = 1)
}
\arguments{
\item{n}{Numeric vector of counts.}
\item{denom}{Denominator: a single positive finite number.}
\item{digits}{Non-negative whole number of decimal places.}
}
\value{
A character vector the same length as \code{n}.
}
\description{
Formats \code{n} out of \code{denom} as \code{"n (pct\%)"}, the way counts appear
in a summary table.
}
\examples{
format_n_pct(c(12, 30), denom = 86)
format_n_pct(5, denom = 86, digits = 0)
}
\seealso{
Other formatting helpers:
\code{\link[=format_mean_sd]{format_mean_sd()}}
}
\concept{formatting helpers}
NAMESPACE: Adds the export entry:
# Generated by roxygen2: do not edit by hand
export(format_mean_sd)
export(format_n_pct)
Both files begin with an explicit header: % Generated by roxygen2: do not edit by hand or # Generated by roxygen2: do not edit by hand. Any manual modifications made directly to these files will be overwritten on the next call to devtools::document().
If you have pre-existing manual documentation files that lack the roxygen header, roxygen2 will not overwrite them. It displays a message such as Skipping NAMESPACE: It already exists and was not generated by roxygen2, ensuring hand-crafted configuration is protected until you choose to opt in.
Markdown in roxygen blocks
In early versions of roxygen2, text formatting required raw Rd commands (\code{...}, \emph{...}, \link{...}). Modern roxygen2 supports standard Markdown formatting:
- Inline code:
`formatC()`becomes\code{formatC()}. - Function links:
[formatC()]generates\code{\link[=formatC]{formatC()}}. - Text emphasis:
**bold**becomes\strong{bold}and*italic*becomes\emph{italic}. - Lists and sections: Markdown bullet lists and headings (
## Details) translate directly to Rd.
Markdown processing is disabled by default in the core roxygen2::roxygenise() engine. When you initialise a package with usethis::create_package(), usethis enables it by inserting this line in DESCRIPTION:
Roxygen: list(markdown = TRUE)
In roxygen2 8.x, configuration fields can also be specified using the Config/roxygen2/ prefix. The vignette vignette("rd-formatting") documents the equivalent field:
Config/roxygen2/markdown: TRUE
If neither field is present in DESCRIPTION, backticks and Markdown links are left as literal characters in the .Rd output.
Examples are executable documentation
Examples demonstrate API usage and are run during R CMD check when their conditions allow it. An unhandled error in an executed example makes the check fail. A condition such as @examplesIf interactive() skips its body during a noninteractive check; ordinary examples do not assert their printed result unless the package supplies a reference output file. Use tests for assertions about return values.
If an example throws an unhandled error during check execution, R CMD check fails with ERROR:
* checking examples ... ERROR
Running examples in ‘tflformat-Ex.R’ failed
The error most likely occurred in:
> format_n_pct(5, denom = 86, digits = -1)
Error: `digits` must be a single non-negative whole number.
Execution halted
To maintain informative examples while keeping package checks clean, follow these guidelines:
- Demonstrate expected errors with
try(): When showing users how input validation works, wrap the call intry():
# Demonstrates error handling without stopping check execution
try(format_n_pct(5, denom = 86, digits = -1))- Conditional execution with
@examplesIf: If an example requires interactive execution, an internet connection, or an environment variable (such as a database URL), guard it with@examplesIf:
#' @examplesIf interactive()
#' format_mean_sd(c(64, 71, 80))In roxygen2 8.1.0, this wraps the example in the Rd file as:
\dontshow{if (interactive()) withAutoprint(\{ # examplesIf}
format_mean_sd(c(64, 71, 80))
\dontshow{\}) # examplesIf}
This formatting call is gated only to illustrate the tag; it has no interactive dependency. In a real package, give such a call an ordinary @examples tag so it runs during checks.
- Avoid
\donttest{}as a hiding place: A common misconception is that wrapping slow or fragile code in\donttest{}prevents check failures. While baseR CMD checkskips\donttest{}by default,R CMD check --as-cranexecutes all\donttest{}examples. Becausedevtools::check()passes--as-cranby default (cran = TRUE),\donttest{}blocks are run during your standard development check. - Reserve
\dontrun{}for non-runnable code:\dontrun{}comments out example code during extraction. Reserve it strictly for code that cannot run in an automated environment, such as examples requiring interactive file selectors or external hardware tokens.
Pitfalls and roxygen2 8.x gotchas
2. devtools::check() may skip documenting
With roxygen2 8.x, new packages record Config/roxygen2/version instead of RoxygenNote, and devtools 2.5.2 then skips its automatic document() step without saying so. Run devtools::document() before devtools::check(), or use check(document = TRUE); the previous post shows the details.
You can also check whether documentation is stale with roxygen2::needs_roxygenize(), which compares the modification times of .Rd files with the source files they were generated from.
3. Combining @export with @noRd produces undocumented objects
If you tag a helper function with @export and @noRd, roxygen2 adds the function to NAMESPACE but writes no .Rd file. In R CMD check, this triggers a WARNING:
* checking for missing documentation entries ... WARNING
Undocumented code objects:
‘helper_fn’
All user-level objects in a package should have documentation entries.
If a function is exported, it must have reference documentation. If a function is an internal implementation detail, use @noRd and omit @export.
4. First-run link resolution messages
When you add a Markdown link in @seealso to another function in the same package (such as [format_mean_sd()]), the first run of devtools::document() on a clean package may display an informational message:
✖ format.R:27: @seealso Could not resolve link to topic "format_mean_sd".
ℹ If this is an in-package link, this is normal. Once "format_mean_sd" is documented, this warning goes away.
This is expected behavior. On the initial pass, roxygen2 evaluates links before the destination .Rd file exists on disk. On the second pass, once the destination topic has been indexed, roxygen2 resolves the cross-reference without messages.
5. Keeping generated files synchronized
Documentation drift occurs when developers modify code in R/ but forget to run devtools::document() before committing changes. The roxygenize hook from {precommit} (described in hooks, formatting, and linting) runs roxygen2::roxygenise() before a commit. If it changes .Rd or NAMESPACE files, the hook fails that attempt; review and stage the generated changes, then retry the commit.
Companion code
View roxygen-demo.R · Download
Creates a temporary R package with documented formatting helpers, runs roxygen2::roxygenise(), inspects generated .Rd files and NAMESPACE exports, tests conditional example extraction, and demonstrates how missing parameter tags are caught by tools::checkDocFiles().
roxygen-demo.R
# Demonstrate function documentation with roxygen2 in a minimal package.
# Run from the project root:
# Rscript posts/roxygen2-documentation/scripts/roxygen-demo.R
demo_source <- c(
"#' Format a count and percentage",
"#'",
"#' Formats `n` out of `denom` as `\"n (pct%)\"`, the way counts appear",
"#' in a summary table.",
"#'",
"#' @param n Numeric vector of counts.",
"#' @param denom Denominator: a single positive finite number.",
"#' @param digits Non-negative whole number of decimal places.",
"#' @returns A character vector the same length as `n`.",
"#' @family formatting helpers",
"#' @export",
"#' @examples",
"#' format_n_pct(c(12, 30), denom = 86)",
"#' format_n_pct(5, denom = 86, digits = 0)",
"format_n_pct <- function(n, denom, digits = 1) {",
" if (!is.numeric(denom) || length(denom) != 1L ||",
" !is.finite(denom) || denom <= 0) {",
" stop(\"`denom` must be a single positive finite number.\", call. = FALSE)",
" }",
" check_digits(digits)",
" pct <- formatC(100 * n / denom, format = \"f\", digits = digits)",
" paste0(n, \" (\", pct, \"%)\")",
"}",
"",
"#' Format a mean and standard deviation",
"#'",
"#' @param x Numeric vector.",
"#' @inheritParams format_n_pct",
"#' @returns A character string of the form `\"mean (sd)\"`.",
"#' @family formatting helpers",
"#' @seealso [formatC()] for the underlying number formatting.",
"#' @export",
"#' @examplesIf interactive()",
"#' format_mean_sd(c(64, 71, 80))",
"format_mean_sd <- function(x, digits = 1) {",
" check_digits(digits)",
" m <- formatC(mean(x, na.rm = TRUE), format = \"f\", digits = digits)",
" s <- formatC(stats::sd(x, na.rm = TRUE), format = \"f\", digits = digits)",
" paste0(m, \" (\", s, \")\")",
"}",
"",
"#' Validate digits argument",
"#' @noRd",
"check_digits <- function(digits) {",
" if (!is.numeric(digits) || length(digits) != 1L ||",
" !is.finite(digits) || digits < 0 || digits != floor(digits)) {",
" stop(\"`digits` must be a single non-negative whole number.\", call. = FALSE)",
" }",
" invisible(TRUE)",
"}"
)
make_demo_package <- function(path = file.path(tempdir(), "tflformat")) {
usethis::create_package(path, rstudio = FALSE, open = FALSE)
writeLines(demo_source, file.path(path, "R", "format.R"))
path
}
document_package <- function(path) {
roxygen2::roxygenise(path)
invisible(list.files(file.path(path, "man"), full.names = FALSE))
}
rd_file <- function(path, topic) {
file.path(path, "man", paste0(topic, ".Rd"))
}
rd_arguments <- function(file) {
parsed <- tools::parse_Rd(file)
args_tag <- Filter(function(x) attr(x, "Rd_tag") == "\\arguments", parsed)
if (length(args_tag) == 0L) {
return(character())
}
items <- Filter(function(x) attr(x, "Rd_tag") == "\\item", args_tag[[1]])
vapply(items, function(it) as.character(it[[1]]), character(1))
}
namespace_exports <- function(path) {
parseNamespaceFile(basename(path), dirname(path))$exports
}
example_code <- function(file) {
lines <- capture.output(tools::Rd2ex(file))
lines[!grepl("^###", lines) & nzchar(trimws(lines))]
}
undocumented_arguments <- function(path) {
tools::checkDocFiles(dir = path)
}
drop_param <- function(path, param) {
format_file <- file.path(path, "R", "format.R")
code <- readLines(format_file, warn = FALSE)
pattern <- paste0("#'\\s+@param\\s+", param, "\\b")
writeLines(code[!grepl(pattern, code)], format_file)
}
run_demo <- function() {
demo_dir <- file.path(tempdir(), "tflformatdemo")
if (dir.exists(demo_dir)) {
unlink(demo_dir, recursive = TRUE)
}
on.exit(unlink(demo_dir, recursive = TRUE), add = TRUE)
message("1. Creating demo package...")
make_demo_package(demo_dir)
message("2. Running roxygen2::roxygenise()...")
document_package(demo_dir)
message("3. Generated Rd files in man/:")
print(list.files(file.path(demo_dir, "man")))
message("4. NAMESPACE exports:")
print(namespace_exports(demo_dir))
message("5. Arguments documented in format_mean_sd.Rd:")
rd_path <- rd_file(demo_dir, "format_mean_sd")
print(rd_arguments(rd_path))
message("6. Example code in format_mean_sd.Rd:")
print(example_code(rd_path))
message("7. Dropping @param denom and re-documenting...")
drop_param(demo_dir, "denom")
document_package(demo_dir)
message("8. Undocumented arguments reported by tools::checkDocFiles():")
print(undocumented_arguments(demo_dir))
}
if (sys.nframe() == 0L) {
run_demo()
}Sources
Standards & R manuals
- Writing R Extensions (§1.3.1 Checking packages): cran.r-project.org/doc/manuals/r-release/R-exts.html#Checking-packages
- Writing R Extensions (§2.1.1 Documenting functions): cran.r-project.org/doc/manuals/r-release/R-exts.html#Documenting-functions
- Writing R Extensions (§1.5.1 Specifying imports and exports): cran.r-project.org/doc/manuals/r-release/R-exts.html#Specifying-imports-and-exports
- CRAN Repository Policy: cran.r-project.org/web/packages/policies.html
Software engineering references
- JSDoc Getting Started: jsdoc.app/about-getting-started
- TypeDoc, Doc Comments: typedoc.org/documents/Doc_Comments.html
- PEP 257 Docstring Conventions: peps.python.org/pep-0257/
- Sphinx autodoc extension: sphinx-doc.org/en/master/usage/extensions/autodoc.html
- Python doctest module: docs.python.org/3/library/doctest.html
R package development guides
- R Packages (2e), Function documentation: r-pkgs.org/man.html
- roxygen2, Documenting functions: roxygen2.r-lib.org/articles/rd-functions.html
- roxygen2, (R)Markdown support: roxygen2.r-lib.org/articles/rd-formatting.html
- roxygen2, Reusing documentation: roxygen2.r-lib.org/articles/reuse.html
- roxygen2, Indexing and cross-references: roxygen2.r-lib.org/articles/index-crossref.html
- roxygen2 release notes: roxygen2.r-lib.org/news/index.html
Package documentation
- roxygen2: roxygen2.r-lib.org · CRAN page
- devtools: devtools.r-lib.org · CRAN page
- usethis: usethis.r-lib.org · CRAN page
- pkgload: pkgload.r-lib.org · CRAN page
- withr: withr.r-lib.org · CRAN page
- riskmetric: pharmar.github.io/riskmetric · CRAN page
- precommit: lorenzwalthert.github.io/precommit/articles/available-hooks.html · CRAN page