3

Arguments of lm function can be obtained by using:

args(lm)

Output

function (formula, data, subset, weights, na.action, method = "qr", 
    model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
    contrasts = NULL, offset, ...) 
NULL

Questions

How to get:

lm (formula, data, subset, weights, na.action, method = "qr", 
    model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
    contrasts = NULL, offset, ...) 

with the description (Not complete help) of each Argument to be used in Sweave or knitr. Thanks

Edited

Using funExtract function provided by @Ananda, I'm very close to my desired result. Here is code of my Rnw file with output.

\documentclass{article}
\usepackage[T1]{fontenc}

\begin{document}

Arguments for lm

<< label = funExtract, echo = TRUE, results = "hide", tidy = FALSE >>=
funExtract <- function(Function, section = "Usage") {
  A <- deparse(substitute(Function))
  x <- capture.output(tools:::Rd2txt(utils:::.getHelpFile(help(A))))
  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)))]]
  cat(out, sep = "\n")
  invisible(out)
}
@

\vspace{0.5cm}\\
funExtract function output
\vspace{0.25cm}\\
<< label = lm-usage, echo = FALSE, results = "asis" >>=
funExtract(lm, section="Usage:")
@

\vspace{0.5cm}\\
args function output
\vspace{0.25cm}\\
<< label = lm-args, echo = FALSE, results = "asis" >>=
args(lm)
@


\end{document}

Output

enter image description here

Issues with funExtract function output

  1. How to get highlighted output from funExtract function as other code?
  2. How to remove section title form funExtract function output?
MYaseen208
  • 22,666
  • 37
  • 165
  • 309
  • `args(lm)` should still work in Sweave or knitr. What are you failing to do? – Richie Cotton Nov 21 '13 at 13:02
  • 1
    You might want to take a look at `formalArgs(lm)`, `formals(lm)` and `sig(lm)`, the last one being in the `sig` package. – Richie Cotton Nov 21 '13 at 13:04
  • Thanks @AnandaMahto for showing your willingness to spare time on solving first issue. I'm afraid `out <- out[-1]` is also not providing desired results. – MYaseen208 Nov 22 '13 at 10:17
  • See [this](https://gist.github.com/mrdwab/7586769). There's a sample Rnw and Rmd file which should work directly if you have the most recent version of "devtools" installed. If not, replace the first few lines with the `helpExtract` function, also at that page. Good luck. – A5C1D2H2I1M1N2O1R2T1 Nov 23 '13 at 16:19
  • Fantastic: Thanks @AnandaMahto for sparing your time and writing such nice function. Would to like to change your comment as an answer so that I can mark it as correct answer for future users. And also bounty!! – MYaseen208 Nov 23 '13 at 16:43
  • 1
    I have a one-liner solution that I will post later to address all the issues you mentioned. – Yihui Xie Nov 24 '13 at 05:27

3 Answers3

6

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.

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • Nice function. Thanks @Yihui for your excellent work. Width of output from this function can be controlled by something like this `formatR::usage(FUN=lm, width=50)`. `helpExtract` function by @AnandaMahto is more general because it can extract any section of the help file. – MYaseen208 Nov 25 '13 at 13:16
4

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")
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • I tested this new function. This works fine with documentclass article but fails with beamer on my machine. Don't why? – MYaseen208 Nov 23 '13 at 17:54
  • @MYaseen208, I actually don't work with Sweave or Beamer. Please feel free to deconstruct my function and see if you can figure out what works for you. – A5C1D2H2I1M1N2O1R2T1 Nov 23 '13 at 17:58
  • @MYaseen208, it works for me. Use the [template here](http://yihui.name/knitr/demo/beamer/) as a starting point. You'll still probably need to tweak the function if you're using anything other than `type = "s_code"` since the line width of the other sections might not fit on a Beamer slide. – A5C1D2H2I1M1N2O1R2T1 Nov 23 '13 at 18:36
  • Needs modifications for functions like `stats::lm`, `nlme::gls`. – MYaseen208 Nov 23 '13 at 20:06
  • Hello @AnandaMahto: I have a question [here](http://stackoverflow.com/q/26202078/707145) relating to `helpExtract` function. – MYaseen208 Oct 05 '14 at 17:14
2

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...
James
  • 65,548
  • 14
  • 155
  • 193