Printing R help files in the console or in knitr documents

[This article was first published on Noam Ross - R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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) {  
  if (!is.character(topic)) topic <- deparse(substitute(topic))
  helpfile = utils:::.getHelpFile(help(topic))

  hs <- capture.output(switch(format, 
  if(!is.null(lines)) hs <- hs[lines]
  hs <- c(before, hs, after)
  cat(hs, sep="\n")

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 = "
", after = "

<br /> R: General-purpose Optimization<br />

optim R Documentation

General-purpose Optimization


General-purpose optimization based on Nelder–Mead, quasi-Newton and conjugate-gradient algorithms. It includes an option for box-constrained optimization and simulated annealing.


optim(par, fn, gr = NULL, …, method = c(“Nelder-Mead”, “BFGS”, “CG”, “L-BFGS-B”, “SANN”, “Brent”), lower = -Inf, upper = Inf, control = list(), hessian = FALSE)

The function is part of my noamtools package on GitHub, where I keep various convenience functions. Enjoy, and fork if you have improvements!

To leave a comment for the author, please follow the link and comment on their blog: Noam Ross - R. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)