5

Is it possible to include R documentation in knitr output? When using stock datasets, it would be nice to just include the builtin documentation without having to copy and paste it in. The problem appears to be that ? works by side effect and so there is no "result" in a meaningful sense. For example,

```{r}
?mtcars
```

has no output that is trapped by knitr.

Using help(...,help_type) instead of ? doesn't help either. I've tried:

```{r, results='markup'}
help(mtcars, help_type="text")
```

and

```{r, results='asis'}
help(mtcars, type="html")
```

with the same result. (In the latter case, knitr did trap the output ## starting httpd help server ... done, which is basically just a message about the side effect.)

In other words, is there a way to extract R help in plain text or HTML?

Livius
  • 3,240
  • 1
  • 17
  • 28

3 Answers3

5

To answer your specific question, "Is there a way to extract R help in plain text or HTML?", the answer would be to use a combination of Rd2HTML or Rd2txt from the "tools" package, with a little bit of help from .getHelpFile from "utils".

For HTML:

tools:::Rd2HTML(utils:::.getHelpFile(help(mtcars)))

For txt:

tools:::Rd2txt(utils:::.getHelpFile(help(mtcars)))

By the sounds of it, though, you should be able to use the function I've linked to in the comment above. For instance, to include the text from the "Description" section of the "mtcars" help page, you would use something along the lines of:

```{r, echo=FALSE, results='asis'}
cat(helpExtract(mtcars, section = "Desc", type = "m_text"))
```
CL.
  • 14,577
  • 5
  • 46
  • 73
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • `Rd2HTML` is actually the better variant for me because it best preserves all of the formatting (and the code is similar for anybody looking at the Rmd file). To avoid having to include the R help stylesheet, you need to set `stylesheet=""`. – Livius Jun 10 '14 at 17:59
  • 6
    @Livius Partially inspired by this post, I have made it possible to automatically display the help page or some specific sections in **knitr** documents now. Please see https://github.com/yihui/printr and http://yihui.name/printr Thanks! – Yihui Xie Sep 10 '14 at 04:26
3

I think you can get what you want by hacking the pager option as follows:

pfun <- function(files, header, title, delete.file) {
    all.str <- do.call("c",lapply(files,readLines))
    cat(all.str,sep="\n")
}
orig_pager <- options(pager=pfun)
help("mtcars")
options(orig_pager)

(you can return the character vector from the function instead of cat()ing it if you prefer).

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
2

Use printr, e.g.

library(printr)
help(mtcars)
detach('package:printr', unload = TRUE)
CL.
  • 14,577
  • 5
  • 46
  • 73
Dmitry Zotikov
  • 2,133
  • 15
  • 12