chribonn
chribonn

Reputation: 457

R markdown file: include help information

I would like to include at the end of the R markdown documention the help page about the mtcars dataset.

In my file I included the following:

```{r}
?mtcars
```

When I compile the markdown (output is to PDF - knitr), upon processing this instruction the help page comes up in my browser but the resulting pdf lacks this section.

Is there a way I could acheive this other then copying from one place to the other?

Thank you.

Upvotes: 7

Views: 1595

Answers (1)

Heather Turner
Heather Turner

Reputation: 3314

We can adapt Yihui Xie's static_help function to get the html source for a given help file

static_help <- function(pkg, topic, out, links = tools::findHTMLlinks()) {
  pkgRdDB = tools:::fetchRdDB(file.path(find.package(pkg), 'help', pkg))
  force(links)
  tools::Rd2HTML(pkgRdDB[[topic]], out, package = pkg,
                 Links = links, no_links = is.null(links))
}

If we write the source to a temporary file we can then read it back in and strip off the header and footer, giving you the body of the help file to include in your markdown document

```{r, echo = FALSE, results = "asis"}
static_help <- function(pkg, topic, out, links = tools::findHTMLlinks()) {
  pkgRdDB = tools:::fetchRdDB(file.path(find.package(pkg), 'help', pkg))
  force(links)
  tools::Rd2HTML(pkgRdDB[[topic]], out, package = pkg,
                 Links = links, no_links = is.null(links))
}
tmp <- tempfile()
static_help("datasets", "mtcars", tmp)
out <- readLines(tmp)
headfoot <- grep("body", out)
cat(out[(headfoot[1] + 1):(headfoot[2] - 1)], sep = "\n")
```

EDIT

The above solution produced HTML output, whereas the question actually asked for PDF output. We can adapt the above to return latex output instead; this time the only-post-editing required is to switch % for \n

```{r, echo = FALSE, results = "asis"}
static_help <- function(pkg, topic, out, links = tools::findHTMLlinks()) {
  pkgRdDB = tools:::fetchRdDB(file.path(find.package(pkg), 'help', pkg))
  force(links)
  tools::Rd2latex(pkgRdDB[[topic]], out, package = pkg,
                  Links = links, no_links = is.null(links))
}
tmp <- tempfile()
static_help("datasets", "mtcars", tmp)
out <- readLines(tmp)
out <- gsub("%", "\n", out, fixed = TRUE)
cat(out, sep = "\n")
```

However the .Rd files depend on Rd.sty. The simplest way to get LaTeX to find Rd.sty is to put a copy in the same directory as your .Rmd file. Then you need to define a custom template to replace the default pandoc LaTeX template. Again, the simplest solution is to put a copy of the default template in the same directory as your .Rmd file, then modify it by replacing everything between the \documentclass command and the \begin{document} command (lines 2 - 145) with the command

\usepackage{Rd}

Finally modify the metadata of your .Rmd file to use the new template

---
output:
    pdf_document:
        template: template.tex
---

Upvotes: 4

Related Questions