Extracting arguments of an R function to use in knitr

隐身守侯 提交于 2019-12-01 08:32:25

I had written a function and posted it as an answer earlier (as noted in the question itself), but wasn't entirely happy with the inconsistencies or the requirement that it had to be used with "markdown" to be used successfully. After a little bit more work, this is the function that I came up with:

helpExtract <- function(Function, section = "Usage", type = "m_code", ...) {
  A <- deparse(substitute(Function))
  x <- capture.output(tools:::Rd2txt(utils:::.getHelpFile(help(A, ...)),
                                     options = list(sectionIndent = 0)))
  B <- grep("^_", x)                    ## section start lines
  x <- gsub("_\b", "", x, fixed = TRUE) ## remove "_\b"
  X <- rep(FALSE, length(x))
  X[B] <- 1
  out <- split(x, cumsum(X))
  out <- out[[which(sapply(out, function(x) 
    grepl(section, x[1], fixed = TRUE)))]][-c(1, 2)]
  while(TRUE) {
    out <- out[-length(out)]
    if (out[length(out)] != "") { break }
  } 

  switch(
    type,
    m_code = c("```r", out, "```"),
    s_code = c("<<>>=", out, "@"),
    m_text = paste("    ", out, collapse = "\n"),
    s_text = c("\\begin{verbatim}", out, "\\end{verbatim}"),
    stop("`type` must be either `m_code`, `s_code`, `m_text`, or `s_text`")
  )
}

Quite a mouthful, and it's not entirely DRY... but I wanted to capture four scenarios and this was the quickest idea that came to mind. The four scenarios I anticipate are:

  1. Document type is markdown and user is extracting a code block (type = "m_code")
  2. Document type is markdown and user is extracting a non-code section (type = "m_text")
  3. Document type is Sweave and user is extracting a code block (type = "s_code")
  4. Document type is Sweave and user is extracting a non-code section (type = "s_text")

The function extracts the output of Rd2txt. I picked that over the other formats (HTML, LaTeX) to allow me to use a single function to get what I was after and not have to create multiple functions.


Usage

Usage is different depending on if you're creating a "Sweave" (.Rnw) or a "markdown" (.Rmd) document.

  1. Markdown

    Insert your code in a code chunk that looks something like this (maybe one day I'll add different methods, but not now):

    ```{r, echo=FALSE, results='asis'}
    cat(helpExtract(cor), sep = "\n")
    ```
    
  2. Sweave

    Pretend you are inserting a "child" document that should be included in the main document using Sexpr{knit_child(.)}

    \Sexpr{knit_child(textConnection(helpExtract(cor, type = "s_code")), 
    options = list(tidy = FALSE, eval = FALSE))}
    

I've created a Gist that includes the function, a sample Rmd file and an sample Rnw file. Feel free to leave comments and suggestions here on Stack Overflow (since Gist comments are pretty much meaningless since they don't notify the user when a comment is posted).


If you're trying to refer to a function from a package that is not currently loaded, the usage of helpExtract should be something like:

helpExtract(gls, package = "nlme")

I have a function usage() in the formatR package that captures the arguments of a function. For now, you have to use the development version (>= 0.10.3).

For knitr, I also have a recent change (i.e. please also test its development version on Github) so that you can the display function usage much more easily: you can use the new chunk option code to input code into a chunk.

Put the two pieces together, you will be able to write a code chunk like this:

<<test, code=formatR::usage(lm), eval=FALSE>>=
@

The reason that these feature came up recently was that I happened to need them by myself as well. I wanted to display the usage of functions with syntax highlighting. This solution is portable to all document formats that knitr supports, not limited to Rnw.

You can use Rd_db to get the Rd data from a package.

x <- Rd_db("stats")

Extract the lm help from this:

lmhelp <- x[basename(names(x))=="lm.Rd"]

Then use capture.output and Rd2latex to get latex of the help page:

lmhelptex <- capture.output(Rd2latex(lmhelp[[1]]))

And pull out the segments you want to include in your rnw file:

lmhelptex[do.call(":",as.list(grep("Usage",lmhelptex)))]
[1] "\\begin{Usage}"                                                    
[2] "\\begin{verbatim}"                                                 
[3] "lm(formula, data, subset, weights, na.action,"                     
[4] "   method = \"qr\", model = TRUE, x = FALSE, y = FALSE, qr = TRUE,"
[5] "   singular.ok = TRUE, contrasts = NULL, offset, ...)"             
[6] "\\end{verbatim}"                                                   
[7] "\\end{Usage}"  

lmhelptex[do.call(":",as.list(grep("Arguments",lmhelptex)))]
 [1] "\\begin{Arguments}"                                                                           
 [2] "\\begin{ldescription}"                                                                        
 [3] "\\item[\\code{formula}] an object of class \\code{\"\\LinkA{formula}{formula}\"} (or one that"
 [4] "can be coerced to that class): a symbolic description of the"                                 
 [5] "model to be fitted.  The details of model specification are given"                            
 [6] "under `Details'."                                                                             
 [7] ""                                                                                             
 [8] "\\item[\\code{data}] ...snip...
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!