(This article was first published on Noam Ross - R, and kindly contributed to R-bloggers)
table tbody {border-top:2px; border-bottom:2px;}
table thead {border-bottom:1px;}
Yesterday, I was creating a knitr docume...
(This article was first published on Noam Ross - R, and kindly contributed to R-bloggers)
table tbody {border-top:2px; border-bottom:2px;}
table thead {border-bottom:1px;}
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 = "", after = "")
R: General-purpose Optimization
optim
R Documentation
General-purpose Optimization
Description
General-purpose optimization based on Nelder–Mead, quasi-Newton and conjugate-gradient algorithms. It includes an option for box-constrained optimization and simulated annealing.
Usage
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 his blog: Noam Ross - R.
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...