[R] Sweave and backslashes

cls59 sharpsteen at mac.com
Fri Feb 6 01:35:46 CET 2009

Hello Everyone,

I am an avid Sweave user and I am trying to pretty print floating point
numbers for latex output. For example in my document, I would like:

4.2\cdot 10^-{8}

Instead of:


The Hmisc package has a nice function for doing this- but Hmisc has a ton of
dependencies and has proved very unportable to the various machines I work
on. So, I set out to write my own function that just uses basic R commands,
it looks like this:

latexNum <- function (x,dig=4,sci=T) 
    x <- format(x,digits=dig,scientific=sci)
         x <- gsub("e\\+00","",x)
         x <- gsub("e\\-0([0-9]*)","\\\\cdot 10^{-\\1}",x)
	 x <- gsub("e\\-([0-9]*)","\\\\cdot 10^{-\\1}",x)
	 x <- gsub("e\\+0([0-9]*)","\\\\cdot 10^{\\1}",x)
	 x <- gsub("e\\+([0-9]*)","\\\\cdot 10^{\\1}",x)

Everything works nicely, if I type

> latexNum(4*10^-3)

I get

[1] "4\\cdot10^{-3}"

And the following:

> cat(latexNum(4*10^-3))



However the following in a .Rnw file:


Only produces this in the .tex output file:

$4cdot 10^{-3}$\\

No amount of extra backslashing seems to help. Any idea why my escapes are
not being respected?

Charlie Sharpsteen
Environmental Resources Engineering
Humboldt State University
View this message in context: http://www.nabble.com/Sweave-and-backslashes-tp21864385p21864385.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list