假设我有两个函数
f
和 g
,并且在我的 roxygen2
文档中,我希望 @examples
的 g
extend f
的示例。
如果我手写的话,会是这样的:
#' 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
}
您会看到
@examples
的 g
部分与 f
的部分相同,只是多了一行修改。
最初我以为我可以简单地使用
@inherit f examples
并修改示例,但这不起作用(一旦添加单独的 @examples
标签,它就会忽略继承的示例)。
在阅读了有关重用文档的小插图之后,我认为最好的方法是编写一个函数generate_example
,比如说,它创建示例脚手架并从内部调用它
@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
}
但这会在我的文档中放置一个文字 `r generate_example()`
(即使它有效,将 R 代码编写为字符串也会非常麻烦)。定义在多个地方使用的示例脚手架/模板的规范方法是什么?
example.R
),然后使用
@example path/to/example.R
标签并使用
@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
}