% Printing R help files in the console or in knitr documents % Noam Ross % 13-06-18 10:30:34
Yesterday, I was creating a knitr
document based on a script, and was looking
for a way to include content from an R help file. The script,
which was a teaching document, had a help()
command for when the author wanted
to refer readers to R documentation. I wanted that text in my final document,
though.
There's no standard way to do this in R, but with some help from
Stack Overflow
and Scott Chamberlain, I figured
out I needed some functions hidden in the depths of the tools
package. So I
wrote this function:
help_console <- function(topic, format=c("text", "html", "latex", "Rd"), lines=NULL, before=NULL, after=NULL) { format=match.arg(format) if (!is.character(topic)) topic <- deparse(substitute(topic)) helpfile = utils:::.getHelpFile(help(topic)) hs <- capture.output(switch(format, text=tools:::Rd2txt(helpfile), html=tools:::Rd2HTML(helpfile), latex=tools:::Rd2latex(helpfile), Rd=tools:::prepare_Rd(helpfile) ) ) if(!is.null(lines)) hs <- hs[lines] hs <- c(before, hs, after) cat(hs, sep="\n") invisible(hs) }
help_console
prints the help file to the console or lets you assign the help
file text to a character. Below, I use it to dynamically print the start of
the help file for the optim()
function as quoted HTML (note that the knitr
chunk has the option results='asis')
:
help_console(optim, "html", lines=1:25, before="<blockquote>", after="</blockquote>")
The function is part of my noamtools
package on
GitHub,
where I keep various convenience functions. Enjoy, and fork if you have
improvements!
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.