r - 为不在包中的 R6 类创建 Rd 文档文件
问题描述
我正在尝试创建一些包含一些 R6 类的脚本的文档。例如,我从这里使用名为“Person”的 R6Class:https ://www.tidyverse.org/blog/2019/11/roxygen2-7-0-0/
我正在使用此功能https://stackoverflow.com/a/59073260/12166017创建文档,而无需创建包。是否也可以将其用于 R6Classes,或者是否有其他方法可以实现这一点?使用提到的功能,我总是得到一个错误R6 Class (Person) without source references.
tidyverse官方博客https://www.tidyverse.org/blog/2019/11/roxygen2-7-0-0/写Roxygen: list(r6 = FALSE)
在DESCRIPTION文件中的解决方法因为我没有包等等没有说明文件。
解决方案
一种方法是劫持 roxygen2 的一些未导出函数,为记录在案的 R6 类创建块对象并写入Rd
文件。然后可以使用该tools
包对其进行解析并写入 html。
这是一个非常粗略的概念证明,要求您的 R6 定义位于独立文件中,并且不采用任何参数来允许保存到特定位置等,但可以对其进行调整和扩展以适应:
document_R6 <- function(R_file)
{
blocks <- lapply(roxygen2:::tokenize_file(R_file), roxygen2:::block_set_env,
env = .GlobalEnv)
blocks <- roxygen2:::order_blocks(blocks)
roclet <- roxygen2:::roclet("rd")
my_rd <- suppressWarnings(roxygen2:::roclet_process(roclet, blocks))
my_rd <- my_rd[[1]]$format()
rd_file <- tempfile()
writeLines(my_rd, rd_file)
tools::Rd2HTML(tools::parse_Rd(rd_file),
gsub("\\.R$", ".html", R_file))
}
因此,如果我们有以下文件,取自您的链接:
人.R
#' R6 Class representing a person
#'
#' A person has a name and a hair color.
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
#' Create a new person object.
#' @param name Name.
#' @param hair Hair color.
#' @return A new `Person` object.
initialize = function(name = NA, hair = NA) {
self$name <- name
self$hair <- hair
self$greet()
},
#' @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
},
#' @description
#' Say hi.
greet = function() {
cat(paste0("Hello, my name is ", self$name, ".\n"))
}
)
)
然后我们可以这样做:
document_R6("Person.R")
以下是生成的“Person.html”文件的屏幕截图,该文件与“Person.R”位于同一目录中:
推荐阅读
- javascript - 手动调用 React render() 函数?
- c++ - 使用 ffmpeg 以编程方式读取 fMP4
- java - 如何将 System.currentMillisSeconds 转换为 TemporalAccessor
- powershell - 验证安装期间提供的用户凭据(预安装)
- docker - 如何修复mysql错误日志中的“mbind:不允许操作”
- c++ - 如果一个为高,则将字节中的所有位设置为高
- javascript - 输入高尔夫分数和相关计算时如何指定表格行
- mysql - 如何根据聚合函数的结果更新属性
- javascript - 如果满足条件,则在另一个转换期间添加一个并发转换
- r - 在 R 中使用 rpart() 时使用的实际字符 (0)