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

如何用Roxygen2为R6类及其方法生成可访问的文档?

给R6类和方法分别生成独立帮助文档的实现方案

我刚好做过类似的R包开发,给你分享下怎么实现这个需求——既能通过?Person查看类的完整文档,又能通过?set_hair直接访问单个方法的说明,完全符合你的要求!

1. 先完善R6类的基础文档

你已经写了一部分类的roxygen注释,我帮你补全完整结构,确保类的文档清晰易懂:

#' This is my Person class
#' @title Person Class
#' @docType class
#' @description A class representing a person with name and hair colour attributes,
#' along with methods to modify these attributes.
#' @field name Character scalar: Name of the person
#' @field hair Character scalar: Hair colour of the person
#'
#' @section Public Methods:
#' \describe{
#'   \item{\code{new(name, hair = "black")}}{Initialize a new Person object}
#'   \item{\code{set_hair(value)}}{Update the hair colour of the person}
#'   \item{\code{greet()}}{Return a greeting message from the person}
#' }
#' @export
Person <- R6::R6Class(
  "Person",
  public = list(
    name = NULL,
    hair = NULL,
    initialize = function(name, hair = "black") {
      self$name <- name
      self$hair <- hair
    },
    set_hair = function(value) {
      self$hair <- value
    },
    greet = function() {
      cat(paste0("Hello, my name is ", self$name, ".\n"))
    }
  )
)

这里的关键是在@section Public Methods里列出所有公开方法,让用户通过?Person就能快速了解类的全部功能。

2. 给单个方法添加独立文档并导出

要让?set_hair这类方法能单独被查询,你需要给每个方法单独写roxygen注释块,并且用@export标签导出方法(R6方法本质是绑定到类的函数,导出后就能生成独立帮助页)。

比如给set_hair和greet方法添加独立注释:

#' Set hair colour of a Person object
#' @title Update Person's Hair Colour
#' @description Modify the hair colour attribute of an existing Person instance.
#' @param self A Person object (automatically passed when using the method via `$`)
#' @param value Character scalar: New hair colour to assign
#' @examples
#' # Create a Person instance
#' john <- Person$new("John")
#' # Change hair colour
#' john$set_hair("brown")
#' # Check updated value
#' john$hair
#' @export
set_hair <- function(self, value) {
  self$hair <- value
}

#' Generate a greeting from a Person
#' @title Person Greeting
#' @description Return a printed greeting message from the Person instance.
#' @param self A Person object (automatically passed when using the method via `$`)
#' @examples
#' jane <- Person$new("Jane")
#' jane$greet()
#' @export
greet <- function(self) {
  cat(paste0("Hello, my name is ", self$name, ".\n"))
}

小细节提醒:R6类里的方法绑定到类后,用户既可以通过john$set_hair("blonde")的面向对象写法调用,也能直接用set_hair(john, "blonde")调用,两种方式都能生效。

3. 生成并验证文档

完成上述代码后,在你的R包项目里运行:

devtools::document()

这时候R会自动生成类和方法的帮助文档:

  • 输入?Person:可以看到类的完整说明、字段、方法列表
  • 输入?set_hair:可以看到这个方法的详细参数、示例
  • 输入?greet:同理查看问候方法的文档

注意事项

  • 只给公开方法添加独立文档和导出,私有方法(放在private列表里的)不需要这么做
  • 方法注释里的self参数要说明清楚,虽然用户用$调用时不用手动传,但帮助文档里需要明确
  • 示例代码一定要写,这样用户能快速理解方法的用法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:28:34