### Including External Example Files Source: https://roxygen2.r-lib.org/articles/rd-functions Use @example to insert code from separate files into the documentation, keeping examples organized and maintainable. ```r '@example path/relative/to/package/root' ``` -------------------------------- ### Providing Executable Examples Source: https://roxygen2.r-lib.org/articles/rd-functions Use @examples to provide R code demonstrating function usage. Ensure examples are self-contained and work without errors. ```r '@examples fruit <- c("apple", "banana", "pear", "pineapple") str_detect(fruit, "a") str_detect(fruit, "^a") str_detect(fruit, "a$") # Also vectorised over pattern str_detect("aecfg", letters)' ``` ```r '@examples # Row sizes must be compatible when column-binding try(bind_cols(tibble(x = 1:3), tibble(y = 1:2)))' ``` -------------------------------- ### Conditional Examples with @examplesIf Source: https://roxygen2.r-lib.org/articles/rd-functions Use @examplesIf to include code that only runs in specific environments, like interactive sessions. This prevents R CMD check failures while still providing examples. ```r '@examplesIf interactive() browseURL("https://roxygen2.r-lib.org")' ``` -------------------------------- ### tag_examples Source: https://roxygen2.r-lib.org/reference/tag_parsers Parses a tag value specifically for examples. ```APIDOC ## tag_examples ### Description Parses a tag value specifically for examples. ### Usage ```r TAG_EXAMPLES(x) ``` ### Arguments * `x`: A [roxy_tag](https://roxygen2.r-lib.org/reference/roxy_tag.md) object to parse. ### Value A [roxy_tag](https://roxygen2.r-lib.org/reference/roxy_tag.md) object with the `val` field set to the parsed value. ``` -------------------------------- ### Example roxygen2 tags for tips Source: https://roxygen2.r-lib.org/articles/extending Illustrates the input roxygen2 tags for a custom '@tip' functionality. ```r '@tip The mean of a logical vector is the proportion of \code{TRUE} values. '@tip You can compute means of dates and date-times! ``` -------------------------------- ### Load Installed Package Source: https://roxygen2.r-lib.org/reference/load Uses the already installed version of the package for the highest fidelity loading. This strategy requires the package to be installed externally. ```r load_installed(path) ``` -------------------------------- ### Define an R function with roxygen2 tags Source: https://roxygen2.r-lib.org/reference/rd_roclet This example demonstrates how to document an R function using roxygen2 tags. The tags specify the function's purpose, parameters, return value, and export status. The `@examples` tag includes runnable code that will be included in the generated documentation. ```r add <- function(x, y) { x + y } ``` -------------------------------- ### load_installed Source: https://roxygen2.r-lib.org/reference/load Loads the installed version of the package. Provides the highest fidelity but requires the package to be installed externally. ```APIDOC ## load_installed ### Description Uses the installed version of the package. This is the highest fidelity strategy, but requires work outside of roxygen2. ### Usage ```r load_installed(path) ``` ### Arguments - path: Path to source package ``` -------------------------------- ### Documenting a String Length Function in R Source: https://roxygen2.r-lib.org/llms.txt Example of documenting an R function using roxygen2 comments. Includes a description, parameter inheritance, return value, see also, export tag, and examples. ```r #' The length of a string #' #' Technically this returns the number of "code points", in a string. One #' code point usually corresponds to one character, but not always. For example, #' an u with a umlaut might be represented as a single character or as the #' combination a u and an umlaut. #' #' @inheritParams str_detect #' @return A numeric vector giving number of characters (code points) in each #' element of the character vector. Missing string have missing length. #' @seealso [stringi::stri_length()] which this function wraps. #' @export #' @examples #' str_length(letters) #' str_length(NA) #' str_length(factor("abc")) #' str_length(c("i", "like", "programming", NA)) str_length <- function(string) { } ``` -------------------------------- ### Install roxygen2 Package Source: https://roxygen2.r-lib.org/llms.txt Installs the roxygen2 package from CRAN or the development version from GitHub using pak. ```r install.packages("roxygen2") ``` ```r pak::pak("r-lib/roxygen2") ``` -------------------------------- ### Example of custom @memo tag usage Source: https://roxygen2.r-lib.org/articles/extending Illustrates how to use the custom @memo tag with a specific headline and description. ```r '@memo [EFFICIENCY] Currently brute-force; find better algorithm.' ``` -------------------------------- ### Set roxygen2 Options in DESCRIPTION Source: https://roxygen2.r-lib.org/reference/load_options Example of setting roxygen2 options directly in the DESCRIPTION file using Config/roxygen2/ fields. ```text Config/roxygen2/markdown: TRUE Config/roxygen2/load: installed ``` -------------------------------- ### Documenting Coupled Parameters in left_join() Source: https://roxygen2.r-lib.org/articles/reuse Example of documenting multiple, tightly coupled parameters (`x`, `y`) together in `left_join()`, which must be inherited as a group. ```r #' @param x,y A pair of data frames, data frame extensions (e.g. a tibble), or #' lazy data frames (e.g. from dbplyr or dtplyr). See *Methods*, below, for #' more details. ``` -------------------------------- ### Roxygen2 Reuse Tag Examples Source: https://roxygen2.r-lib.org/reference/tags-reuse Demonstrates the syntax for various roxygen2 reuse tags. These tags help in managing and inheriting documentation across different parts of a package. ```r #' @describeIn ${1:destination} ${2:description} ``` ```r #' @eval ${1:r-code} ``` ```r #' @evalRd ${1:r-code} ``` ```r #' @includeRmd man/rmd/${1:filename}.Rmd ``` ```r #' @inherit ${1:source} ${2:components} ``` ```r #' @inheritDotParams ${1:source} ${2:arg1 arg2 arg3} ``` ```r #' @inheritParams ${1:source} ${2:arg1 arg2 arg3} ``` ```r #' @inheritSection ${1:source} ${2:section name} ``` ```r #' @order ${1:number} ``` ```r #' @rdname ${1:topic-name} ``` ```r #' @template ${1:path-to-template} ``` ```r #' @templateVar ${1:name} ${2:value} ``` -------------------------------- ### Basic Roxygen Block Example Source: https://roxygen2.r-lib.org/articles/roxygen2 A roxygen block is a sequence of lines starting with #'. The first lines form the introduction, followed by tags starting with @. The block ends when it hits R code. ```r #' Add together two numbers #' #' @param x A number. #' @param y A number. #' @return A number. #' @export #' @examples #' add(1, 1) #' add(10, 1) add <- function(x, y) { x + y } ``` -------------------------------- ### Example Usage of roxy_block Source: https://roxygen2.r-lib.org/reference/roxy_block Demonstrates how to create and inspect a roxy_block object using parse_text. ```APIDOC ## Examples ``` r # The easiest way to see the structure of a roxy_block is to create one # using parse_text: text <- " #' This is a title #' #' @param x,y A number #' @export f <- function(x, y) x + y " # parse_text() returns a list of blocks, so I extract the first block <- parse_text(text)[[1]] block #> [:6] #> $tag #> [line: 2] @title 'This is a title' {parsed} #> [line: 4] @param 'x,y A number' {parsed} #> [line: 5] @export '' {parsed} #> [line: 6] @usage '' {parsed} #> [line: 6] @.formals '' {parsed} #> [line: 6] @backref '' {parsed} #> $call f <- function(x, y) x + y #> $object #> $topic f #> $alias f ``` ``` -------------------------------- ### Generated Rd File Example Source: https://roxygen2.r-lib.org/articles/roxygen2 This is an example of an .Rd file generated by roxygen2 from the R code snippet above. Rd files are a special file format loosely based on LaTeX. ```rd % Generated by roxygen2: do not edit by hand % Please edit documentation in ./ \name{add} \alias{add} \title{Add together two numbers} \usage{ add(x, y) } \arguments{ \item{x}{A number.} \item{y}{A number.} } \value{ A number. } \description{ Add together two numbers } \examples{ add(1, 1) add(10, 1) } ``` -------------------------------- ### Markdown Code Blocks in Roxygen Source: https://roxygen2.r-lib.org/articles/rd-formatting Demonstrates how to include multi-line code blocks within roxygen documentation using triple backticks. This is useful for showing examples or longer code snippets. ```r #' ``` #' pkg <- make_packages( #' foo1 = { f <- function() print("hello!") ; d <- 1:10 }, #' foo2 = { f <- function() print("hello again!") ; d <- 11:20 } #' ) #' foo1::f() #' foo2::f() #' foo1::d #' foo2::d #' dispose_packages(pkg) #' ``` ``` -------------------------------- ### Roxygen2 Function Documentation Tags Source: https://roxygen2.r-lib.org/reference/tags-rd-functions This snippet lists common Roxygen2 tags used for documenting R functions. It covers tags for descriptions, examples, conditional examples, suppressing documentation, parameters, raw Rd content, return values, titles, and usage. ```r #' @description${1:A short description...} #' @details${1:Additional details...} #' @example ${1:path}.R #' @examples${1:# example code} #' @examplesIf ${1:condition}${2:# example code} #' @noRd #' @param ${1:name} ${2:description} #' @rawRd ${1:rd} #' @return ${1:description} #' @returns ${1:description} #' @title ${1:title} #' @usage ${1:fun}(${2:arg1, arg2 = default, ...}) ``` -------------------------------- ### roxy_tag Constructor Source: https://roxygen2.r-lib.org/reference/roxy_tag Constructs a tag object. Arguments starting with '.' are reserved for internal usage. ```APIDOC ## Function: roxy_tag ### Description Constructor for tag objects. ### Usage ```r roxy_tag(tag, raw, val = NULL, file = NA_character_, line = NA_character_) ``` ### Arguments * **tag** (character) - Tag name. * **raw** (character) - Raw tag value, a string. * **val** (any, optional) - Parsed tag value, typically a character vector, but sometimes a list. Usually filled in by `tag_parsers`. * **file** (character, optional) - Location of the tag. * **line** (character, optional) - Location of the tag. ``` -------------------------------- ### Roxygen Block with Markdown Support Source: https://roxygen2.r-lib.org/articles/rd-formatting Example of a roxygen documentation block that utilizes Markdown syntax. Markdown support can be toggled per block using `@md` or `@noMd`. ```r #' Use roxygen to document a package #' #' This function is a wrapper for the [roxygen2::roxygenize()] function from #' the roxygen2 package. See the documentation and vignettes of #' that package to learn how to use roxygen. #' #' @param pkg package description, can be path or package name. See #' [as.package()] for more information. #' @param clean,reload Deprecated. #' @inheritParams roxygen2::roxygenise #' @seealso [roxygen2::roxygenize()], `browseVignettes("roxygen2")` #' @export ``` -------------------------------- ### Roxygen2 NAMESPACE Tag Examples Source: https://roxygen2.r-lib.org/reference/tags-namespace Demonstrates the usage of various roxygen2 tags for managing package NAMESPACE. These tags control function exports, S3/S4 method exports, class exports, and imports from other packages. ```r #' @export #' @exportS3Method ${1:package}::${2:generic} #' @exportClass ${1:class} #' @exportMethod ${1:generic} #' @exportPattern ${1:pattern} #' @import ${1:package} #' @importClassesFrom ${1:package} ${2:class} #' @importMethodsFrom ${1:package} ${2:generic} #' @importFrom ${1:package} ${2:function} #' @useDynLib ${1:package} #' @evalNamespace ${1:r-code} #' @rawNamespace ${1:namespace directives} ``` -------------------------------- ### Get section from topic Source: https://roxygen2.r-lib.org/articles/extending Demonstrates how to retrieve a specific section from a roxygen2 topic object. Useful for inspecting or manipulating documentation sections programmatically. ```r topic$get_section("tip") ``` -------------------------------- ### Loading roxygen2 Options Source: https://roxygen2.r-lib.org/reference/load_options Demonstrates how to load roxygen2 options for a package. Options can be set in the DESCRIPTION file or in `man/roxygen/meta.R`. ```APIDOC ## Usage ``` r load_options(base_path = ".") roxy_meta_get(key = NULL, default = NULL) ``` ### Arguments - base_path: Path to package. - key: Key of the options, e.g. `"packages"`. - default: Default value. ### Possible options - `roclets` ``: giving names of [roclets](https://roxygen2.r-lib.org/reference/roclet.md) to run. See [`roclet_find()`](https://roxygen2.r-lib.org/reference/roclet_find.md) for details. - `packages` ``: packages to load that implement new tags. - `load` ``: how to load R code. See [load](https://roxygen2.r-lib.org/reference/load.md) for details. - `old_usage` ``: use old style usage formatting? - `markdown` ``: translate markdown syntax to Rd? - `r6` ``: document R6 classes? - `current_package` `` (read only): name of package being documented. - `rd_family_title` ``: overrides for `@family` titles. See the *rd-functions* vignette for details: [`vignette("rd-functions")`](https://roxygen2.r-lib.org/articles/rd-functions.md) - `knitr_chunk_options` ``: default chunk options used for knitr. - `restrict_image_formats` ``: if `TRUE` then PDF images are only included in the PDF manual, and SVG images are only included in the HTML manual. (This only applies to images supplied via markdown.) ### How to set Either set in `DESCRIPTION` using `Config/roxygen2/` fields: Config/roxygen2/markdown: TRUE Config/roxygen2/load: installed Or if you need more complex options (like `rd_family_title` or `knitr_chunk_options`), put them in `man/roxygen/meta.R`: list( rd_family_title = list(models = "Model functions"), knitr_chunk_options = list(fig.width = 7) ) ### See also Other extending: [`parse_package()`](https://roxygen2.r-lib.org/reference/parse_package.md), [`rd_section()`](https://roxygen2.r-lib.org/reference/rd_section.md), [`roc_proc_text()`](https://roxygen2.r-lib.org/reference/roc_proc_text.md), [`roclet_find()`](https://roxygen2.r-lib.org/reference/roclet_find.md), [`roxy_block()`](https://roxygen2.r-lib.org/reference/roxy_block.md), [`roxy_tag()`](https://roxygen2.r-lib.org/reference/roxy_tag.md), [`roxy_tag_rd()`](https://roxygen2.r-lib.org/reference/roxy_tag_rd.md), [`tag_parsers`](https://roxygen2.r-lib.org/reference/tag_parsers.md), [`tags_list()`](https://roxygen2.r-lib.org/reference/tags_list.md) ``` -------------------------------- ### Load Package with pkgload Source: https://roxygen2.r-lib.org/reference/load Simulates package loading using pkgload::load_all() for high fidelity, especially with S4 objects. Requires the package to be compiled. ```r load_pkgload(path) ``` -------------------------------- ### Documenting a Parameter in arrange() Source: https://roxygen2.r-lib.org/articles/reuse This snippet shows the basic documentation for the `.data` parameter in the `arrange()` function, serving as a source for inheritance. ```r #' @param .data A data frame, data frame extension (e.g. a tibble), or a #' lazy data frame (e.g. from dbplyr or dtplyr). See *Methods*, below, for #' more details. #' @param ... <[`data-masking`][rlang::args_data_masking]> Variables, or #' functions of variables. Use [desc()] to sort a variable in descending #' order. arrange <- function(.data, ...) {} ``` -------------------------------- ### Load Package by Sourcing Files Source: https://roxygen2.r-lib.org/reference/load Simulates package loading by attaching dependencies and sourcing R/ files. This method does not require compilation and was the default in older roxygen2 versions. ```r load_source(path) ``` -------------------------------- ### Documenting an S3 Generic with a Methods Section Source: https://roxygen2.r-lib.org/articles/rd-S3 For more complex S3 generics, use a dedicated '# Methods' section to provide detailed information about available methods, listing them via inline R code. Requires doclisting in Suggests. ```r #' Frobnpolicate an object #' #' @description #' `frobnpolicate()` does ... #' #' # Methods #' `frobnpolicate()` is an S3 generic with methods available for the following #' classes: #' #' `r doclisting::methods_list("frobnpolicate")` ``` -------------------------------- ### Get Tag Metadata Source: https://roxygen2.r-lib.org/reference/tags_list Retrieves metadata for available tags. ```APIDOC ## Function: tags_metadata ### Description Retrieves metadata for all available tags. ### Usage ```r tags_metadata() ``` ``` -------------------------------- ### Documenting Function Parameters Source: https://roxygen2.r-lib.org/articles/rd-functions Use @param to describe function inputs, specifying type and purpose. Include default values and possible values for clarity. ```r '@param pattern Pattern to look for. The default interpretation is a regular expression, as described in `vignette("regular-expressions")`. Use [regex()] for finer control of the matching behaviour. @param string Input vector. Either a character vector, or something coercible to one.' ``` ```r '@param na.rm Remove missing values? If `FALSE` (the default), the result will be `NA` if any element of `string` is `NA`.' ``` ```r '@param side Side on which to remove whitespace: `"left"`, `"right"`, or `"both"` (the default).' ``` ```r '@param whitespace_only A boolean. * `TRUE` (the default): wrapping will only occur at whitespace. * `FALSE`: can break on any non-word character (e.g. `/`, `-`).' ``` ```r '@param x,y Numeric vectors.' ``` -------------------------------- ### Get tag metadata Source: https://roxygen2.r-lib.org/reference/tags_list Use `tags_metadata()` to obtain detailed metadata for all available roxygen2 tags. ```r tags_metadata() ``` -------------------------------- ### Set roxygen2 Options in meta.R Source: https://roxygen2.r-lib.org/reference/load_options Example of setting more complex roxygen2 options, such as rd_family_title or knitr_chunk_options, in man/roxygen/meta.R. ```r list( rd_family_title = list(models = "Model functions"), knitr_chunk_options = list(fig.width = 7) ) ``` -------------------------------- ### load_pkgload Source: https://roxygen2.r-lib.org/reference/load Loads package code using pkgload::load_all() for high fidelity, especially with S4 objects. Requires package compilation. ```APIDOC ## load_pkgload ### Description Simulates package loading using `pkgload::load_all()`. Offers high fidelity handling of code that uses S4, but requires that the package be compiled. ### Usage ```r load_pkgload(path) ``` ### Arguments - path: Path to source package ``` -------------------------------- ### Documenting Dynamically Added Methods Source: https://roxygen2.r-lib.org/articles/rd-R6 Document methods added dynamically using $set() by placing a roxygen block directly above the $set() call. ```r #' @description #' Say goodbye. Person$set("public", "goodbye", function() { cat(paste0("Goodbye from ", self$name, ".\n")) }) ``` -------------------------------- ### Enable Markdown Support in DESCRIPTION Source: https://roxygen2.r-lib.org/articles/rd-formatting Add this entry to your package's DESCRIPTION file to enable Markdown support for roxygen2 documentation. If using devtools/usethis, consider `usethis::use_roxygen_md()`. ```text Config/roxygen2/markdown: TRUE ``` -------------------------------- ### Roxygen2 Image Generation Source: https://roxygen2.r-lib.org/articles/rd-formatting Example of embedding a plot using a knitr code chunk in Roxygen2 documentation. Plots are saved as PNG files in the `man/figures` directory. ```r ' ```{r iris-pairs-plot} pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species", pch = 21, bg = c("red", "green3", "blue")[unclass(iris$Species)]) ``` ' ``` -------------------------------- ### Generated Rd output for tips Source: https://roxygen2.r-lib.org/articles/extending Shows the resulting Rd format for the custom '@tip' tags. ```latex \section{Tips and tricks}{ \itemize{ \item The mean of a logical vector is the proportion of \code{TRUE} values. \item You can compute means of dates and date-times! } } ``` -------------------------------- ### env_package Source: https://roxygen2.r-lib.org/reference/parse_package Creates a temporary environment for parsing a package. ```APIDOC ## env_package ### Description Provides a default environment for parsing a package. ### Usage ```r env_package(path) ``` ### Arguments - path: Path to the root directory of a package. ``` -------------------------------- ### Roxygen2 Markdown and Rd Interaction Source: https://roxygen2.r-lib.org/articles/rd-formatting Illustrates a potential issue where Markdown parsing might unintentionally create lists if a line starts with a number followed by a dot. ```r 'You can see more about this topic in the book cited below, on page # 42. Clearly, the numbered list that starts here is not intentional. ' ``` -------------------------------- ### Document R Package with roxygen2 Source: https://roxygen2.r-lib.org/articles/rd-packages Use the `"_PACKAGE"` sentinel to document the package itself. This automatically includes title, description, authors, and URLs from the DESCRIPTION file. Place this in `{pkgname}-package.R` and use `@keywords internal`. ```r '@keywords internal' "_PACKAGE" ``` -------------------------------- ### Roxygen2 Rd Output with Embedded Code Source: https://roxygen2.r-lib.org/articles/rd-formatting Example of how Roxygen2 processes an R code chunk, showing the generated Rd file content with the output of the R code. ```rd % Generated by roxygen2: do not edit by hand % Please edit documentation in ./ \name{foo} \alias{foo} \title{Title} \usage{ foo() } \description{Title} \details{Details \if{html}{\out{
}}\preformatted{1+1 #> [1] 2} \if{html}{\out{
}} } ``` -------------------------------- ### roxygenize Function Source: https://roxygen2.r-lib.org/reference/roxygenize The `roxygenize` function is the main entry point for generating package documentation. It takes the package directory as input and uses a system of 'roclets' to produce the necessary files. ```APIDOC ## roxygenize ### Description This is the workhorse function that builds manual pages and metadata for a package. It is powered by [roclets](https://roxygen2.r-lib.org/reference/roclet.md), roxygen2's plugin system for producing different types of output. ### Usage ```r roxygenize(package.dir = ".", roclets = NULL, load_code = NULL, clean = FALSE) ``` ### Arguments - **package.dir** (character) - Location of package top level directory. Default is working directory. - **roclets** (character vector or NULL) - Character vector of [roclets](https://roxygen2.r-lib.org/reference/roclet.md) to use. The default, `NULL`, uses the roxygen `roclets` option, which defaults to `c("collate", "namespace", "rd")`. - **load_code** (function or NULL) - A function used to load all the R code in the package directory. The default, `NULL`, uses the strategy defined by the `load` roxygen option, which defaults to [`load_pkgload()`](https://roxygen2.r-lib.org/reference/load.md). - **clean** (logical) - If `TRUE`, roxygen will delete all files previously created by roxygen before running each roclet. ### Value `NULL` ### Details Note that roxygen2 is a dynamic documentation system: it works by inspecting loaded objects in the package. This means that you must be able to load the package in order to document it: see [load](https://roxygen2.r-lib.org/reference/load.md) for details. ``` -------------------------------- ### Load roxygen2 library Source: https://roxygen2.r-lib.org/articles/extending Loads the roxygen2 package for use. This is a common first step when working with roxygen2. ```r library(roxygen2) ``` -------------------------------- ### Markdown Hyperlink Formatting Source: https://roxygen2.r-lib.org/articles/rd-formatting Standard Markdown hyperlinks and URLs within angle brackets are converted to Rd hyperlinks. The Commonmark website and R project website are used as examples. ```r #' See more about the Markdown markup at the #' [Commonmark web site](http://commonmark.org/help) ``` ```r #' The main R web site is at . ``` -------------------------------- ### Creating and Inspecting a roxy_block Source: https://roxygen2.r-lib.org/reference/roxy_block Demonstrates how to create a `roxy_block` object using `parse_text` and inspect its structure. This is useful for understanding how roxygen2 parses documentation comments into structured blocks. ```r text <- " #' This is a title #' #' @param x,y A number #' @export f <- function(x, y) x + y " # parse_text() returns a list of blocks, so I extract the first block <- parse_text(text)[[1]] block ``` -------------------------------- ### Load roxygen2 Options Source: https://roxygen2.r-lib.org/reference/load_options Load roxygen2 options from the package. Use roxy_meta_get() to retrieve specific option values. ```r load_options(base_path = ".") roxy_meta_get(key = NULL, default = NULL) ``` -------------------------------- ### Create a custom documentation tag Source: https://roxygen2.r-lib.org/articles/reuse Define custom tags like `@git` to generate specific Rd sections. This reduces repetition for frequently used documentation patterns. ```r #' @git rebase ``` -------------------------------- ### env_file Source: https://roxygen2.r-lib.org/reference/parse_package Creates a temporary environment for parsing an R file. ```APIDOC ## env_file ### Description Provides a default environment for parsing an R file. ### Usage ```r env_file(file) ``` ### Arguments - file: Path to an R file. ``` -------------------------------- ### Check for Outdated Documentation Source: https://roxygen2.r-lib.org/reference/needs_roxygenize Use needs_roxygenize() to quickly check if any man pages in your package appear to be out of date. Set quiet = TRUE to suppress messages listing the out-of-date files. ```r needs_roxygenize(package.dir = ".", quiet = FALSE) ``` ```r if (FALSE) { needs_roxygenize() } ``` -------------------------------- ### Inheriting Parameters in mutate() and summarise() Source: https://roxygen2.r-lib.org/articles/reuse Demonstrates how `mutate()` and `summarise()` can inherit documentation for the `.data` parameter from `arrange()` using `@inheritParams`. ```r #' @inheritParams arrange mutate <- function(.data, ...) {} ``` ```r #' @inheritParams arrange summarise <- function(.data, ...) {} ``` -------------------------------- ### Specify Source Files with @backref Source: https://roxygen2.r-lib.org/articles/index-crossref Use @backref to specify the original source file location for documentation, substituting the default list of source files. Use one tag per source file. ```r '@backref src/file.cpp' ``` ```r '@backref src/file.h' ``` -------------------------------- ### Initialize namespace roclet Source: https://roxygen2.r-lib.org/reference/namespace_roclet Call `namespace_roclet()` to create a NAMESPACE file. This is the default roclet used by `roxygenize()`. ```r namespace_roclet() ``` -------------------------------- ### Inherit documentation from another package Source: https://roxygen2.r-lib.org/articles/reuse Reuse documentation components from topics in other packages using the `package::function` syntax. Be mindful of the added dependency and potential maintenance overhead. ```r #' @inheritParams package::function ``` ```r #' @inherit package::function ``` ```r #' @inheritSection package::function Section title ``` ```r #' @inheritDotParams package::function ``` -------------------------------- ### Basic Function Documentation Structure Source: https://roxygen2.r-lib.org/articles/rd-functions Demonstrates the standard roxygen2 documentation block for a function, including title, description, and function definition. ```r sum <- function(..., na.rm = TRUE) {} ``` -------------------------------- ### Documenting an S3 Generic with Inline R Code Source: https://roxygen2.r-lib.org/articles/rd-S3 Use this format to document an S3 generic function, mentioning it's a generic and listing available methods using inline R code from the doclisting package. Requires doclisting in Suggests. ```r #' Frobnpolicate an object #' #' @description #' `frobnpolicate()` is an S3 generic that ..., with methods available for #' the following classes: #' #' `r doclisting::methods_list("frobnpolicate")` ``` -------------------------------- ### Documenting an S4 Class with Slots Source: https://roxygen2.r-lib.org/articles/rd-S4 Document an S4 class definition using a roxygen block before `setClass()`. Use `@slot` to describe each slot. Export the class if it's intended for user creation or extension. ```r #' An S4 class to represent a bank account #' #' @slot balance A length-one numeric vector #' @export Account <- setClass("Account", slots = list(balance = "numeric")) ``` -------------------------------- ### Documenting R6 Methods Inline Source: https://roxygen2.r-lib.org/articles/rd-R6 Document methods inline using tags like @description, @param, and @returns. All roxygen comment lines must appear after a tag. ```r Person <- R6::R6Class( "Person", public = list( #' @description #' Create a new person object. #' @param name Name. #' @param hair Hair color. #' @returns A new `Person` object. initialize = function(name = NA, hair = NA) { self$name <- name self$hair <- hair self$greet() }, #' @description #' Change hair color. #' @param val New hair color. set_hair = function(val) { self$hair <- val }, #' @description #' Say hi. greet = function() { cat(paste0("Hello, my name is ", self$name, ".\n")) } ) ) ``` -------------------------------- ### Documenting a Dataset with Roxygen2 Source: https://roxygen2.r-lib.org/articles/rd-datasets Use this roxygen2 block to document a dataset. Quote the dataset name and use `@format` and `@source` tags for detailed information. ```r #' Prices of over 50,000 round cut diamonds #' #' A dataset containing the prices and other attributes of almost 54,000 #' diamonds. The variables are as follows: #' #' @format A data frame with 53940 rows and 10 variables: #' \describe{ #' \item{price}{price in US dollars ($326--$18,823)} #' \item{carat}{weight of the diamond (0.2--5.01)} #' \item{cut}{quality of the cut (Fair, Good, Very Good, Premium, Ideal)} #' \item{color}{diamond colour, from D (best) to J (worst)} #' \item{clarity}{a measurement of how clear the diamond is (I1 (worst), SI2, #' SI1, VS2, VS1, VVS2, VVS1, IF (best))} #' \item{x}{length in mm (0--10.74)} #' \item{y}{width in mm (0--58.9)} #' \item{z}{depth in mm (0--31.8)} #' \item{depth}{total depth percentage = z / mean(x, y) = 2 * z / (x + y) (43--79)} #' \item{table}{width of top of diamond relative to widest point (43--95)} #' } #' #' @source {ggplot2} tidyverse R package. "diamonds" ``` -------------------------------- ### Documenting Dataset Format and Source Source: https://roxygen2.r-lib.org/reference/tags-rd-datasets Use the `@format` tag to describe the structure of your dataset, including column details for data frames. Use the `@source` tag to indicate the origin of the data and any transformations applied. ```r #' @format ${1:description} #' @source ${1:description} ``` -------------------------------- ### Handling Dot Prefix Arguments Source: https://roxygen2.r-lib.org/articles/reuse Explains how `@inheritParams` automatically handles the dot prefix convention, allowing inheritance between arguments like `.x` and `x`. ```r #' @inheritParams arrange #' @param .data <[`data-masking`][rlang::args_data_masking]> Variables, or #' functions of variables. Use [desc()] to sort a variable in descending #' order. #' @param .keep <[`data-masking`][rlang::args_data_masking]> #' @param .before <[`data-masking`][rlang::args_data_masking]> #' @param .after <[`data-masking`][rlang::args_data_masking]> mutate <- function(.data, ..., .keep = "all", .before = NULL, .after = NULL) {} ``` -------------------------------- ### Create Environment for File Source: https://roxygen2.r-lib.org/reference/parse_package Use `env_file()` to create a temporary environment for parsing a specific R file. This environment can be passed to `parse_file()` or `parse_text()`. ```r env_file(file) ``` -------------------------------- ### Documenting Function Outputs Source: https://roxygen2.r-lib.org/articles/rd-functions Use @returns to describe the output of a function. For data frames, explain how the output relates to the input. ```r '@returns A logical vector the same length as `string`.' ``` ```r '@returns An object of the same type as `.data`. The output has the following properties: * Rows are a subset of the input, but appear in the same order. * Columns are not modified. * The number of groups may be reduced (if `.preserve` is not `TRUE`). * Data frame attributes are preserved.' ``` -------------------------------- ### Roxygen2 with Knitr Chunk Options Source: https://roxygen2.r-lib.org/articles/rd-formatting Demonstrates using knitr chunk options like `results="hold"` within Roxygen2 documentation to control code output. ```r ' ```{r results="hold"} names(mtcars) nrow(mtcars) ``` ' ``` -------------------------------- ### roxy_block and helper functions Source: https://roxygen2.r-lib.org/reference/roxy_block This snippet shows the constructor for roxy_block and several helper functions for manipulating roxy_block objects. ```APIDOC ## roxy_block() ### Description Creates a new `roxy_block` object. ### Arguments - **tags**: A list of `roxy_tag` objects. - **file**: Location of the `call` (i.e. the line after the last line of the block). - **line**: Location of the `call` (i.e. the line after the last line of the block). - **call**: Expression associated with block. - **object**: Optionally, the object associated with the block, found by inspecting/evaluating `call`. ## block_has_tags(block, tags) ### Description Checks if a `roxy_block` contains any of the specified `tags`. ### Arguments - **block**: A `roxy_block` to manipulate. - **tags**: A vector of tag names to check for. ## block_get_tags(block, tags) ### Description Retrieves all instances of the specified `tags` from a `roxy_block`. ### Arguments - **block**: A `roxy_block` to manipulate. - **tags**: A vector of tag names to retrieve. ## block_get_tag(block, tag) ### Description Retrieves a single tag from a `roxy_block`. Returns `NULL` if zero tags are found, and throws a warning if more than one is found. ### Arguments - **block**: A `roxy_block` to manipulate. - **tag**: A single tag name. ## block_get_tag_value(block, tag) ### Description Retrieves the value of a single tag from a `roxy_block`. ### Arguments - **block**: A `roxy_block` to manipulate. - **tag**: A single tag name. ``` -------------------------------- ### load_source Source: https://roxygen2.r-lib.org/reference/load Loads package code by attaching dependencies and sourcing files in the R/ directory. Does not require compilation. ```APIDOC ## load_source ### Description Simulates package loading by attaching packages listed in `Depends` and `Imports`, then sources all files in the `R/` directory. This strategy does not need compilation. ### Usage ```r load_source(path) ``` ### Arguments - path: Path to source package ``` -------------------------------- ### Roxygen2 Function Link Syntax Source: https://roxygen2.r-lib.org/articles/rd-formatting Markdown can be used to create links to other help topics within the current package or its dependencies. Different syntaxes are available for linking to functions and topics, with or without specifying custom text. ```r #' [func()] ``` ```r #' [topic] ``` ```r #' [`topic`] ``` ```r #' [pkg::func()] ``` ```r #' [pkg::topic] ``` ```r #' [`pkg::topic`] ``` ```r #' [text][topic] ``` ```r #' [`text`][topic] ``` ```r #' [text][pkg::topic] ``` ```r #' [`text`][pkg::topic] ``` -------------------------------- ### Importing All Functions with @import Source: https://roxygen2.r-lib.org/articles/namespace While possible, importing all functions from a package with @import is generally not recommended due to potential name conflicts. ```r # Example of @import (not recommended for general use) #' @import pkg ``` -------------------------------- ### Selective Parameter Inheritance Source: https://roxygen2.r-lib.org/articles/reuse Illustrates how to inherit specific parameters or exclude parameters using `@inheritParams` with parameter names or ranges. ```r - @inheritParams foo x y ``` ```r - @inheritParams foo -z ``` ```r - @inheritParams foo first:third ``` -------------------------------- ### Configure roxygen2 Load Strategy Source: https://roxygen2.r-lib.org/reference/load Override the default package loading strategy in roxygen2 by setting the 'load' option in the Roxygen configuration. ```r Roxygen: list(load = "source") ``` -------------------------------- ### Running roxygen2 Source: https://roxygen2.r-lib.org/llms.txt Functions for documenting an R package with roxygen2 and checking if documentation needs updates. ```APIDOC ## roxygenize() ### Description Document a package with roxygen2. ### Method Function Call ### Parameters None explicitly documented. ### Request Example ```r roxygenize() ``` ### Response Documentation generated for the package. ``` ```APIDOC ## needs_roxygenize() ### Description Check if documentation needs to be updated. ### Method Function Call ### Parameters None explicitly documented. ### Request Example ```r needs_roxygenize() ``` ### Response Boolean indicating if documentation needs update. ``` ```APIDOC ## load_pkgload(), load_installed(), load_source() ### Description Load package code from different sources (installed, source). ### Method Function Call ### Parameters None explicitly documented. ### Request Example ```r load_source("path/to/package") ``` ### Response Package code loaded. ``` -------------------------------- ### Markdown Sections and Subsections in Roxygen Source: https://roxygen2.r-lib.org/articles/rd-formatting Demonstrates how Markdown headings create sections and subsections within roxygen documentation. Top-level headings create `\section{}`, while level two and above create `\subsection{}` within text-formatting tags. ```r #' @details #' Trim the leading and trailing whitespace from a character vector. #' #' @param x Character vector. #' @return Character vector, with the whitespace trimmed. #' #' @details # This will be a new section #' ... ``` ```r #' @details #' ## Subsection within details #' ### Sub-subsection #' ... text ... ``` -------------------------------- ### Inherit all tags from another topic Source: https://roxygen2.r-lib.org/articles/reuse Use `@inherit` to copy all supported documentation tags from another topic. This is useful for maintaining consistency across related functions. ```r #' @inherit foo ``` -------------------------------- ### Exporting and Documenting an S3 Method Source: https://roxygen2.r-lib.org/articles/rd-S3 Always export S3 methods using @export, even for internal generics, to register them. Document methods with unique behavior or arguments, linking back to the generic. ```r #' @export bizarro.character <- function(x, ...) { letters <- strsplit(x, "") letters_rev <- lapply(letters, rev) vapply(letters_rev, paste, collapse = "", FUN.VALUE = character(1)) } ``` -------------------------------- ### Documenting an R6 Class Source: https://roxygen2.r-lib.org/articles/rd-R6 Document the R6 class definition using a roxygen block before R6Class(). Use @export to make the class available to users. ```r #' R6 Class Representing a Person #' #' A person has a name and a hair color. #' @export Person <- R6::R6Class( "Person", public = list( # ... fields and methods ... ) ) ``` -------------------------------- ### Document S7 Class Constructor Source: https://roxygen2.r-lib.org/articles/rd-S7 Document an S7 class constructor function using roxygen2, specifying parameters, properties, and return values. ```r Range <- new_class( "Range", properties = list( start = class_numeric, end = class_numeric, length = new_property(getter = function(self) self@end - self@start), validator = function(self) { if (self@start > self@end) { "start must be less than or equal to end" } } ) ) ``` -------------------------------- ### Roxygen2 Index and Cross-reference Tags Source: https://roxygen2.r-lib.org/reference/tags-index-crossref Demonstrates the usage of common roxygen2 tags for indexing and cross-referencing documentation. These tags help in organizing help files and improving searchability within R. ```r #' @aliases ${1:alias} #' @backref ${1:path} #' @concept ${1:concept} #' @family ${1:family name} #' @keywords ${1:keyword} #' @references ${1:reference} #' @seealso [${1:func}()] ``` -------------------------------- ### Markdown Inline Code in Roxygen Source: https://roxygen2.r-lib.org/articles/rd-formatting Illustrates using backticks for inline code snippets within roxygen documentation, such as parameter descriptions. ```r #' @param ns Optionally, a named vector giving prefix-url pairs, as #' produced by `xml_ns`. If provided, all names will be explicitly #' qualified with the ns prefix, i.e. if the element `bar` is defined ... ``` -------------------------------- ### Documenting S7 Class Properties Source: https://roxygen2.r-lib.org/reference/tags-rd-S7 Use the `@prop` tag to describe an S7 class property that is not a constructor parameter. This tag helps in providing detailed information about the class structure. ```r #' @prop ${1:name} ${2:description} ``` -------------------------------- ### Create Environment for Package Source: https://roxygen2.r-lib.org/reference/parse_package Use `env_package()` to create a temporary environment for parsing an R package directory. This environment can be passed to `parse_package()`. ```r env_package(path) ``` -------------------------------- ### Specify File Dependencies with @include Source: https://roxygen2.r-lib.org/reference/update_collate Use the @include tag to specify which R files should be sourced before the current file. This ensures that dependencies are loaded in the correct order, especially when using features like S4 classes. ```r NULL #> NULL ``` -------------------------------- ### Markdown Image Formatting Source: https://roxygen2.r-lib.org/articles/rd-formatting Markdown syntax for inline images is supported. Image files must be located in the `man/figures` directory. ```r #' Here is an example plot: #' ![](example-plot.jpg "Example Plot Title") ``` -------------------------------- ### Define custom @memo tag syntax Source: https://roxygen2.r-lib.org/articles/extending Use this syntax to define a custom tag like @memo for adding notes to documentation. ```r '@memo [Headline] Description' ``` -------------------------------- ### Markdown Inline Formatting in Roxygen Source: https://roxygen2.r-lib.org/articles/rd-formatting Shows how to use Markdown for emphasis (*italic*) and strong text (**bold**) within roxygen documentation tags like `@references`. ```r #' @references #' Robert E Tarjan and Mihalis Yannakakis. (1984). Simple #' linear-time algorithms to test chordality of graphs, test acyclicity #' of hypergraphs, and selectively reduce acyclic hypergraphs. #' *SIAM Journal of Computation* **13**, 566-579. ``` ```r #' See `::is_falsy` for the definition of what is _falsy_ #' and what is _truthy_. ``` -------------------------------- ### Document S7 Method with Unique Behavior Source: https://roxygen2.r-lib.org/articles/rd-S7 Document an S7 method that has unique behavior or arguments, linking back to the generic using [generic_name()]. ```r method(size, Range) <- function(x, ...) { x@length } ``` -------------------------------- ### Document ellipsis arguments Source: https://roxygen2.r-lib.org/articles/reuse Use `@inheritDotParams` to document common arguments passed through `...`. This improves usability by providing inline documentation for frequently used parameters without requiring users to look them up elsewhere. ```r #' @inheritDotParams foo ``` ```r #' @inheritDotParams foo a b e:h ``` ```r #' @inheritDotParams foo -x -y ``` -------------------------------- ### Overriding Inherited Parameters in mutate() Source: https://roxygen2.r-lib.org/articles/reuse Shows how to override inherited documentation for the `...` parameter in `mutate()` by providing a specific definition, as its interpretation differs from `arrange()`. ```r #' @inheritParams arrange #' @param ... <[`data-masking`][rlang::args_data_masking]> Name-value pairs. #' The name gives the name of the column in the output. #' #' The value can be: #' #' * A vector of length 1, which will be recycled to the correct length. #' * A vector the same length as the current group (or the whole data frame #' if ungrouped). #' * `NULL`, to remove the column. #' * A data frame or tibble, to create multiple columns in the output. mutate <- function(.data, ...) {} ``` -------------------------------- ### Exporting S3 Method with Import Source: https://roxygen2.r-lib.org/articles/rd-S3 Use `@importFrom` and `@export` when writing methods for generics from imported packages. This ensures the generic is available and the method is exported. ```r #' @importFrom pkg generic #' @export generic.foo <- function(x, ...) {} ```