You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发R包时,如何在同包函数的roxygen2示例中调用其他同包函数?

在R包同函数示例中调用同包函数的正确方法

你遇到的问题核心在于函数的导出状态和命名空间访问规则,以下是对应场景的解决办法:

场景1:testdata()是对外导出的公开函数

如果testdata()是包向用户开放的功能,需先完成导出配置:

  1. 在testdata()的roxygen2注释中添加@export标签,示例如下:
#' 生成测试样本数据
#' @param some_parameters 参数说明
#' @export
testdata <- function(some_parameters) {
  # 函数逻辑代码
}
  1. 运行devtools::document()更新包的NAMESPACE文件,此时testdata()会被加入导出列表。
  2. 之后在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()仅用于包内逻辑,不需要对用户开放:

  1. 不要给testdata()添加@export标签。
  2. 在modify_data()的示例中,使用三个冒号:::访问内部函数:
#' @examples
#' sample_data <- mypackagename:::testdata(some_parameters)
#' sample_data <- modify_data(sample_data)
  1. 注意:运行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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 14:17:44