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

使用roxygen2文档化R6类时如何消除示例重复显示

解决R6类方法示例在文档中重复显示的问题

你遇到的重复问题是因为roxygen2默认会将R6类公共方法的示例同时展示在类的主帮助页面和方法的单独帮助页面中。以下是两种可行的解决方式:

方案1:禁用方法的单独帮助页面(推荐)

如果不需要为方法生成独立的帮助页面,只需在方法的roxygen注释中添加@noRd标签,roxygen2就不会为该方法创建单独的帮助文档,示例只会在类的主页面显示一次。

修改后的代码:

#' R6 Class Representing a Person
#'
#' @description
#' A person has a name and a hair color.
#'
#' @details
#' A person can also greet you.

Person <- R6::R6Class("Person",
                      public = list(

                        #' @field name First or full name of the person.
                        name = NULL,

                        #' @field hair Hair color of the person.
                        hair = NULL,

                        #' @description
                        #' Change hair color.
                        #' @param val New hair color.
                        #' @examples
                        #' P <- Person("Ann", "black")
                        #' P$hair
                        #' P$set_hair("red")
                        #' P$hair
                        #' @noRd
                        set_hair = function(val) {
                          self$hair <- val
                        }
                      ), cloneable = FALSE
)

方案2:手动控制类文档的方法展示

如果需要保留方法的单独帮助页面,同时避免类主文档重复显示示例,可以手动在类的roxygen注释中编写方法概述,阻止roxygen自动合并方法的完整文档(包括示例)。

修改后的代码:

#' R6 Class Representing a Person
#'
#' @description
#' A person has a name and a hair color.
#'
#' @details
#' A person can also greet you.
#'
#' @section Methods:
#' \describe{
#'   \item{\code{set_hair(val)}}{修改头发颜色,详见方法专属帮助页面}
#' }
#'
#' @examples
#' # 类的基础使用示例
#' P <- Person("Ann", "black")
#' P$name

Person <- R6::R6Class("Person",
                      public = list(

                        #' @field name First or full name of the person.
                        name = NULL,

                        #' @field hair Hair color of the person.
                        hair = NULL,

                        #' @description
                        #' Change hair color.
                        #' @param val New hair color.
                        #' @examples
                        #' P <- Person("Ann", "black")
                        #' P$hair
                        #' P$set_hair("red")
                        #' P$hair
                        set_hair = function(val) {
                          self$hair <- val
                        }
                      ), cloneable = FALSE
)

这样类的主文档只会显示你自定义的方法概述,方法的示例只会出现在它的单独帮助页面中,不会重复。

内容的提问来源于stack exchange,提问作者Rüdiger Keiner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 07:55:19