【问题标题】:creating Rd documentation files for R6 classes not in a package为不在包中的 R6 类创建 Rd 文档文件
【发布时间】:2020-10-01 10:03:49
【问题描述】:

我正在尝试创建一些包含一些 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/在DESCRIPTION文件中写Roxygen: list(r6 = FALSE)的解决方法不行,因为我没有包,所以没有DESCRIPTION文件。

【问题讨论】:

    标签: r function roxygen2 r6


    【解决方案1】:

    这样做的一种方法是劫持 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))
    }
    

    如果我们有以下文件,取自您的链接:

    Person.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”位于同一目录中:


    【讨论】:

      猜你喜欢
      • 2012-10-31
      • 2012-11-29
      • 1970-01-01
      • 2017-07-24
      • 2013-09-26
      • 2011-04-16
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多