Translate: 将R函数帮助添加到Quarto文档中

huangapple go评论82阅读模式
英文:

R functions help into a quarto document

问题

The following code gives the examples [tag:R] codes along their output for first six topics from [tag:stats] [tag:R] library.


title: "Help"
format: pdf

#| echo: false
#| class-output: r
library(purrr)
map(
      .x             = ls("package:stats", all = FALSE)[1:6] 
    , .f             = example
    , package        = "stats"
    , character.only = TRUE
    , type           = "html"
    )

Translate: 将R函数帮助添加到Quarto文档中

I want to tweak this output a little bit.

Expected Output

Wondering how to add each topic title as a section and then its corresponding code and output.

Edited

The helpExtract from SOfun [tag:R] package can be used to extract specified portions of [tag:R] help files for use in [tag:Sweave] or [tag:R-markdown] documents.

remotes::install_github("mrdwab/SOfun")

library(SOfun)

helpExtract(
Function = acf
, section = c("Description", "Usage", "Arguments", "Details", "Value", "Examples")1
, type = c("m_code", "m_text", "s_code", "s_text")[2]
)

However, can't figure out how to use this function to extract topic title.

Edited (2023-04-19)

@Julian's solution is effective for the [tag:stats] [tag:R] package, but it does not function properly with the [tag:meta] [tag:R] package. When attempting to use it with the [tag:meta] [tag:R] package, the following error is generated:

Error in purrr::map():i In index: 1.Caused by error in file():! cannot open the connectionError in vctrs_vec_compat(.y, .purrr_user_env): object 'topic_title' not foundError in cat(res, sep = "\n"): object 'res' not found1

英文:

The following code gives the examples [tag:R] codes along their output for first six topics from [tag:stats] [tag:R] library.

---
title: "Help"
format: pdf
---

```{r}
#| echo: false
#| class-output: r
library(purrr)
map(
      .x             = ls("package:stats", all = FALSE)[1:6] 
    , .f             = example
    , package        = "stats"
    , character.only = TRUE
    , type           = "html"
    )
```

Translate: 将R函数帮助添加到Quarto文档中

I want to tweak this output a little bit.

Expected Output

Wondering how to add each topic title as a section and then its corresponding code and output.

Edited

The helpExtract from SOfun [tag:R] package can be used to extract specified portions of [tag:R] help files for use in [tag:Sweave] or [tag:R-markdown] documents.

remotes::install_github("mrdwab/SOfun")

library(SOfun)

helpExtract(
    Function = acf
  , section  = c("Description", "Usage", "Arguments", "Details", "Value", "Examples")[1] 
  , type     = c("m_code", "m_text", "s_code", "s_text")[2]
  )

However, can't figured out how to use this function to extract topic title.

Edited (2023-04-19)

@Julian's solution is effective for the [tag:stats] [tag:R] package, but it does not function properly with the [tag:meta] [tag:R] package. When attempting to use it with the [tag:meta] [tag:R] package, the following error is generated:

> Error in purrr::map():i In index: 1.Caused by error in file():! cannot
> open the connectionError in vctrs_vec_compat(.y, .purrr_user_env):
> object 'topic_title' not foundError in cat(res, sep = "\n"): object
> 'res' not found1

答案1

得分: 2

这是你想要的吗?我添加了一个目录来查看章节是否符合预期(代码思路来自这里这里):

---
title: "帮助"
format: pdf
toc: true
number-sections: true
---
#| echo: false

# https://stackoverflow.com/questions/8379570/get-functions-title-from-documentation
pkg_topic <- function(package, topic, file = NULL) {
  # 找到主题名称/别名对应的“file”名称
  if (is.null(file)) {
    topics <- pkg_topics_index(package)
    topic_page <- subset(topics, alias == topic, select = file)$file

    if(length(topic_page) < 1)
      topic_page <- subset(topics, file == topic, select = file)$file

    stopifnot(length(topic_page) >= 1)
    file <- topic_page[1]    
  }

  rdb_path <- file.path(system.file("help", package = package), package)
  tools:::fetchRdDB(rdb_path, file)
}

pkg_topics_index <- function(package) {
  help_path <- system.file("help", package = package)

  file_path <- file.path(help_path, "AnIndex")
  if (length(readLines(file_path, n = 1)) < 1) {
    return(NULL)
  }

  topics <- read.table(file_path, sep = "\t", 
    stringsAsFactors = FALSE, comment.char = "", quote = "", header = FALSE)

  names(topics) <- c("alias", "file") 
  topics[complete.cases(topics), ]
}
#| output: asis
#| echo: false

topic <- ls("package:stats", all = FALSE)[1:6]
topic_title <- topic |> 
  purrr::map( \(function_name) {
    target <- gsub("^.+/library/(.+)/help.+$", "\", utils:::index.search("stats", 
                                                                  find.package()))
    doc.txt <- pkg_topic(target, function_name)  # 假设Hadley的两个函数都在这里

    return(doc.txt[[1]][[1]][1])
  })


res <- purrr::map2_chr(topic, topic_title, \(topic, topic_title) {
    knitr::knit_child(text = c(
      "# `r topic_title`",
      "",
      "```{r}",
      "#| echo: false",
      "#| class-output: r",
      "example(topic, package = 'stats', character.only = TRUE, type = 'html')",
      "```",
      "",
      ""
    ), envir = environment(), quiet = TRUE)
  })

cat(res, sep = '\n')

Translate: 将R函数帮助添加到Quarto文档中


<details>
<summary>英文:</summary>

Is this what you want? I added a toc to see whether the chapters are as intended (code idea comes from [here](https://github.com/quarto-dev/quarto-cli/issues/2370) and [here](https://stackoverflow.com/questions/8379570/get-functions-title-from-documentation)):


    ---
    title: &quot;Help&quot;
    format: pdf
    toc: true
    number-sections: true
    ---
    
    
    ```{r}
    #| echo: false
    
    # https://stackoverflow.com/questions/8379570/get-functions-title-from-documentation
    pkg_topic &lt;- function(package, topic, file = NULL) {
      # Find &quot;file&quot; name given topic name/alias
      if (is.null(file)) {
        topics &lt;- pkg_topics_index(package)
        topic_page &lt;- subset(topics, alias == topic, select = file)$file
    
        if(length(topic_page) &lt; 1)
          topic_page &lt;- subset(topics, file == topic, select = file)$file
    
        stopifnot(length(topic_page) &gt;= 1)
        file &lt;- topic_page[1]    
      }
    
      rdb_path &lt;- file.path(system.file(&quot;help&quot;, package = package), package)
      tools:::fetchRdDB(rdb_path, file)
    }
    
    pkg_topics_index &lt;- function(package) {
      help_path &lt;- system.file(&quot;help&quot;, package = package)
    
      file_path &lt;- file.path(help_path, &quot;AnIndex&quot;)
      if (length(readLines(file_path, n = 1)) &lt; 1) {
        return(NULL)
      }
    
      topics &lt;- read.table(file_path, sep = &quot;\t&quot;, 
        stringsAsFactors = FALSE, comment.char = &quot;&quot;, quote = &quot;&quot;, header = FALSE)
    
      names(topics) &lt;- c(&quot;alias&quot;, &quot;file&quot;) 
      topics[complete.cases(topics), ]
    }
    ```
    
    
    
    ```{r}
    #| output: asis
    #| echo: false
    
    topic &lt;- ls(&quot;package:stats&quot;, all = FALSE)[1:6]
    topic_title &lt;- topic |&gt; 
      purrr::map( \(function_name) {
        target &lt;- gsub(&quot;^.+/library/(.+)/help.+$&quot;, &quot;\&quot;, utils:::index.search(&quot;stats&quot;, 
                                                                      find.package()))
        doc.txt &lt;- pkg_topic(target, function_name)  # assuming both of Hadley&#39;s functions are here
    
        return(doc.txt[[1]][[1]][1])
      })
      
    
    
    res &lt;- purrr::map2_chr(topic, topic_title, \(topic, topic_title) {
        knitr::knit_child(text = c(
          &quot;# `r topic_title`&quot;,
          &quot;&quot;, 
          &quot;```{r}&quot;,
          &quot;#| echo: false&quot;,
          &quot;#| class-output: r&quot;,
          &quot;example(topic, package = &#39;stats&#39;, character.only = TRUE, type = &#39;html&#39;)&quot;,
          &quot;```&quot;,
          &quot;&quot;,
          &quot;&quot;
        ), envir = environment(), quiet = TRUE)
      })
    
    cat(res, sep = &#39;\n&#39;)
    ```

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/Sh6Wa.png




</details>



huangapple
  • 本文由 发表于 2023年4月17日 17:25:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76033607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定