【问题标题】:Can you share examples between functions with rOxygen2?你能用 rOxygen2 分享函数之间的例子吗?
【发布时间】:2019-12-13 17:19:49
【问题描述】:

我知道可以使用 rOxygen 使用 @describeIn@rdname 标签将多个函数分组到同一个文档下。这对于具有相似目的/语法的函数组来说很好。

但是,我正在编写一个包,其中一组函数几乎总是应作为工作流的一部分执行。为了让事情更简洁,我想用一个例子来说明这个工作流程,并为所有涉及的功能展示它。

我需要将这些函数保存在它们单独的文档页面中,因为它们每个都有非常不同的目的、参数并且需要一个非常广泛的文档。我不想通过将所有内容组合在一起来混淆读者。

这有可能吗?例如,我可以拥有一个包含示例代码的文件并将其包含在所有函数文档中吗?

以防万一,我在下面添加了一些虚拟代码。

#' function1
#' 
#' This does stuff
#' 
#' @param a,b a and b
#' @return c
#' @export
#' @examples 
#' # step 1 : do this
#' C <- function1(a,b)
#' 
#' # step 2 : do that
#' D <- function2(C, e, f)
#' 
#' # step 3 : profit.
function1 <- function(a,b){
  return(a+b)
}

#' function2
#' 
#' This also does stuff
#' 
#' @param C could be from function1
#' @param e,f e and f
#' @return d
#' @export
#' @examples 
#' # step 1 : do this
#' C <- function1(a,b)
#' 
#' # step 2 : do that
#' D <- function2(C, e, f)
#' 
#' # step 3 : profit.
function2 <- function(C, e, f){
  return(C+e+f)
}

【问题讨论】:

    标签: r r-package roxygen2


    【解决方案1】:

    我找到了一种方法,方法是使用 Roxygen 的 @eval 标记并将我的示例存储在返回示例代码的函数中。

    所以在一个包中,你会拥有一个像这样的shared_examples.R 文件:

    function_examples <- function()
    {
      ex <- "
    @examples
    # step 1 : do this
    C <- function1(a,b)
    
    # step 2 : do that
    D <- function2(C, e, f)
    
    # step 3 : profit.
    "
      return(strsplit(ex, split = "\n")[[1]]) # needed to have line jumps in the doc
    }
    

    然后,您的实际函数文档将如下所示:

    #' function1
    #' 
    #' This does stuff
    #' 
    #' @param a,b a and b
    #' @return c
    #' @export
    #' @eval function_examples()
    function1 <- function(a,b){
      return(a+b)
    }
    
    #' function2
    #' 
    #' This also does stuff
    #' 
    #' @param C could be from function1
    #' @param e,f e and f
    #' @return d
    #' @export
    #' @eval function_examples()
    function2 <- function(C, e, f){
      return(C+e+f)
    }
    

    现在,示例在这两个函数之间共享!

    我发现这使得集中示例(或函数之间的任何共享文档)变得非常容易,而无需在更新时重复所有内容。

    【讨论】:

      【解决方案2】:

      我认为这是一种更合适的方式。

      你的例子可以

      • 存在于@examples 标签之后
      • 存在于您从文档中获取的 R 脚本中,即

        #' @example man/examples/foo.R

      来源:https://www.r-bloggers.com/code-examples-in-the-r-package-manuals/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-20
        • 1970-01-01
        • 2019-11-17
        • 1970-01-01
        • 2014-06-25
        • 1970-01-01
        相关资源
        最近更新 更多