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

R包开发中如何复用重复的示例代码片段?

R包@examples代码复用方案

问题场景

开发R包时,多个函数的@examples里存在重复代码(比如变量初始化、数据标准化步骤),复制粘贴不仅繁琐,还会导致底层函数变更时,所有用到该代码的示例都要手动更新,极易出错。

可行实现方案

方案1:roxygen2自定义宏(最直接)

roxygen2支持用@macro定义可复用代码块,完美适配你的需求:

  1. 在包的任意R文件(比如R/utils.R)顶部定义公共宏:
#' @macro common_init
#' @examples
#' # 公共初始化代码
#' x <- 1
#' y <- 2
NULL

#' @macro add_example_part
#' @examples
#' @macro common_init
#' z <- add(x, y)
NULL
  1. 在各个函数的文档中直接引用宏:
#' Add two variables together
#'
#' @param x Numeric value for one of the variables
#' @param y Numeric value of the other variable
#' @return A numeric value of the sum of x and y
#' @export
#' @examples
#' @macro add_example_part
add <- function(x, y) {
  x + y
}

#' Multiply two variables together
#'
#' @inheritParams add
#' @return A numeric value of the product of x and y
#' @export
#' @examples
#' @macro common_init
#' product(x, y)
product <- function(x, y) {
  x * y
}

#' Calculates the mean of the summed variable x
#'
#' @param x Sum of variables to calculate the mean from
#' @param n Number of variables that were summed
#' @return A numerical value for the mean of x
#' @export
#' @examples
#' @macro add_example_part
#' n <- 2
#' mean2(z, n)
mean2 <- function(x, n) {
  x*n^-1
}

修改公共宏内容后,所有引用该宏的函数示例会自动同步更新。

方案2:外部示例文件(适合复杂代码片段)

如果公共代码逻辑复杂,或需要单独维护,可把代码放在inst/examples/目录下的文件中:

  1. 创建inst/examples/common_init.R:
# 公共初始化代码
x <- 1
y <- 2
  1. 创建inst/examples/add_example_part.R:
source(system.file("examples/common_init.R", package = "yourpkg"))
z <- add(x, y)
  1. 在函数文档中用@example引用外部文件:
#' Add two variables together
#' ...
#' @export
#' @example inst/examples/add_example_part.R
add <- function(x, y) {x + y}

#' Multiply two variables together
#' ...
#' @export
#' @example inst/examples/common_init.R
#' @examples
#' product(x, y)
product <- function(x, y) {x * y}

#' Calculates the mean of the summed variable x
#' ...
#' @export
#' @example inst/examples/add_example_part.R
#' @examples
#' n <- 2
#' mean2(z, n)
mean2 <- function(x, n) {x*n^-1}

开发阶段需确保包已加载(比如用devtools::load_all()),否则system.file可能找不到路径。

注意事项

  • 宏定义必须放在NULL对象上方,roxygen2才能识别。
  • 涉及包内数据的标准化时,确保公共代码正确引用包内数据(比如用yourpkg::data_name)。
  • 生成文档前,运行devtools::document()更新所有函数的帮助文档。

内容的提问来源于stack exchange,提问作者Baraliuh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 08:25:35