开发R包时,如何在同包函数的roxygen2示例中调用其他同包函数?
在R包同函数示例中调用同包函数的正确方法
你遇到的问题核心在于函数的导出状态和命名空间访问规则,以下是对应场景的解决办法:
场景1:testdata()是对外导出的公开函数
如果testdata()是包向用户开放的功能,需先完成导出配置:
- 在
testdata()的roxygen2注释中添加@export标签,示例如下:
#' 生成测试样本数据 #' @param some_parameters 参数说明 #' @export testdata <- function(some_parameters) { # 函数逻辑代码 }
- 运行
devtools::document()更新包的NAMESPACE文件,此时testdata()会被加入导出列表。 - 之后在
modify_data()的示例中,两种写法均可正常运行:
#' @examples #' sample_data <- testdata(some_parameters) #' sample_data <- modify_data(sample_data)
或者
#' @examples #' sample_data <- mypackagename::testdata(some_parameters) #' sample_data <- modify_data(sample_data)
场景2:testdata()是包内部私有函数
如果testdata()仅用于包内逻辑,不需要对用户开放:
- 不要给
testdata()添加@export标签。 - 在
modify_data()的示例中,使用三个冒号:::访问内部函数:
#' @examples #' sample_data <- mypackagename:::testdata(some_parameters) #' sample_data <- modify_data(sample_data)
- 注意:运行R CMD CHECK时会出现一条NOTE,提示访问了非导出对象,这属于正常情况,若确认
testdata()为内部函数,可忽略该NOTE。
之前报错的原因说明
- 第一种写法报错
could not find function "testdata":因为testdata()未导出,示例运行时仅加载了包的导出命名空间,无法访问内部函数。 - 第二种写法报错
'testdata' is not an exported object from 'namespace:mypackagename':因为::仅能访问包的导出对象,而testdata()未被标记为导出。
内容的提问来源于stack exchange,提问作者ReelSaemon
相关产品推荐
相关产品推荐

