Printing R help files in the console or in knitr documents

June 18, 2013

(This article was first published on Noam Ross - R, and kindly contributed to R-bloggers)

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

<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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Mango solutions

RStudio homepage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training


CRC R books series

Contact us if you wish to help support R-bloggers, and place your banner here.

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)