Romain Francois, Professional R Enthusiast

To content | To menu | To search

Saturday, April 3 2010

embed images in Rd documents

The new help system that was introduced in R 2.10.0 and documented in an article of the R journal is very promising.

One thing that is planned for future versions of R (maybe 2.12.0) is some way to include images into Rd documents using the fig option of the Sexpr macro

Another way is to use data uri and embed the image directly inside the html code, so this morning I played with this and wrapped up this little c library into an R package called base64 and hosted in the Rcpp project at r-forge.

The package allows encoding and decoding files using the Base64 format. It currently has three functions: encode, decode and img. encode and decode do what their name implies, and img produces the html code suitable for embedding the image into an html document.

The help page for img actually contains an image, here is it:

and here is how it is produced:

\details{
\if{html}{
	The following graph is embedded in the document using the \code{img} function	
	
\Sexpr[stage=render,results=rd,echo=FALSE]{
	library( base64 )
	library( grDevices )
	library( graphics )
	library( stats )
	
	pngfile <- tempfile()
	png( pngfile, width = 600, height = 400 )
	plot( 1:100, rnorm(100), pch = 21, bg = "red", cex = 2 )
	dev.off()
	img( pngfile, Rd = TRUE )
}
}

}

Sunday, November 22 2009

new R package : highlight

I finally pushed highlight to CRAN, which should be available in a few days. The package uses the information gathered by the parser package to perform syntax highlighting of R code

The main function of the package is highlight, which takes a number of argument including :

  • file : the file in which the R code is
  • output : some output connection or file name where to write the result (The default is standard output)
  • renderer : a collection of function controlling how to render code into a given markup language

The package ships three functions that create such renderers

  • renderer_html : renders in html/css
  • renderer_latex: renders in latex
  • renderer_verbatim: does nothing

And additionally, the xterm256 package defines a renderer that allows syntax highlighting directly in the console (if the console knows xterm 256 colors)

Let's assume we have this code file (/tmp/code.R)

f <- function( x){
        x + rnorm(1)
}

g <- function(x){}
h <- function(x){}

Then we can syntax highlight it like this :

> highlight( "/tmp/code.R", renderer = renderer_html(), output = "/tmp/code.R.html" )
> highlight( "/tmp/code.R", renderer = renderer_latex(), output = "/tmp/code.R.latex" )

which makes these files : code.R.html and code.R.latex

The package also ships a sweave driver that can highlight code chunks in a sweave document, but I'll talk about this in another post