【问题标题】:R package - @example function can't be tested if the function is not exportedR包-如果未导出函数,则无法测试@example函数
【发布时间】:2015-12-10 08:04:57
【问题描述】:

我正在使用 RStudio 开发一个自定义 R 包,使用 roxygen2 记录。

请考虑这个函数:

#' Get "test"
#'
#' @return String
#' @export
#'
#' @examples getTest()
getTest <- function() {
  return("test")
}

如果我用上面写的函数文档运行R CMD check,一切都很好,check 成功传递。

现在,如果我删除 @export(因为我不希望从包外部看到此功能),我会收到以下错误:

* checking examples ... ERROR
Running examples in 'MyPackageName-Ex.R' failed
The error most likely occurred in:

> ### Name: getTest
> ### Title: Get "test"
> ### Aliases: getTest
> 
> ### ** Examples
> 
> getTest()
Error: could not find function "getTest"
Execution halted

看起来@examples 中的函数测试是从包外运行的!?

如何测试非导出函数的例子?

【问题讨论】:

  • 示例是文档的一部分。文档仅适用于导出的函数。如果您的目标是单元测试,请使用实现该功能的包之一,例如,如果您想留在 hadleyverse 中,请打包 testthat。
  • 您说:“文档仅用于导出的函数”。它是 R 哲学吗?还是 Roxygen2 哲学?因为我也想记录这些未导出的函数,至少对我或我的包的共同开发者来说是这样。并添加一些示例以更好地理解!一种解决方案是使用 testthat 进行单元测试,并将示例添加到 dontrun{} 块中。不过,这并不是那么令人满意..
  • 您应该重新阅读“编写 R 扩展”。我只是使用 cmets 为自己记录未导出的函数。
  • @Ronald 哪个部分?

标签: r


【解决方案1】:

我非常不同意@Roland 的评论,因为有一个接近文档的示例有助于了解我 6 个月后到底在想什么。使用check() 自动检查它意味着它有机会与代码保持同步。我在 R 文档中没有看到任何禁止或劝告记录非导出函数的内容。

幸运的是,您可以使用三冒号 ::: 运算符调用未导出的函数。示例:

 ##' Drop specified dimension from an array
 ##'
 ##' Like drop(x) but only dropping specified dimensions.
 ##' There is no testing that the specified dimensions are actually     singletons.
 ##' @param x array of at least d dimensions
 ##' @param d dimension(s) to drop
 ##' @return array x
 ##' @examples
 ##' x = array(1:4, dim=c(1, 2, 1, 2))
 ##' dx = MAST:::Drop(x, 1)
 ##' stopifnot(all(dim(dx)==c(2,1,2)))
 ##' 
    Drop <- function(x, d){
        dim(x) <- dim(x)[-d]
        x
    }

【讨论】:

  • 同意 - 文档对于我自己和合作开发者和最终用户一样重要。
猜你喜欢
  • 1970-01-01
  • 2011-07-06
  • 2015-11-02
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
  • 2016-04-17
  • 1970-01-01
相关资源
最近更新 更多