在多个 roxygen 块中使用相同的示例模板

问题描述 投票:0回答:1

假设我有两个函数

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 代码编写为字符串也会非常麻烦)。

定义在多个地方使用的示例脚手架/模板的规范方法是什么?

r r-package roxygen2
1个回答
0
投票
啊,一种方法是将示例代码放在一个单独的文件中(比如

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 }
    
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.