Skip to content

Sweave and backslashes

4 messages · cls59, Frank E Harrell Jr, Charles C. Berry +1 more

#
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:

4.2e-08

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)
         
        return(x)
}

Everything works nicely, if I type
I get

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

And the following:
Produces:

4\cdot10^{-3}

However the following in a .Rnw file:

$\Sexpr{latexNum(4*10^-3)}$\\

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
Undergraduate
Environmental Resources Engineering
Humboldt State University
#
cls59 wrote:
Please name the dependencies that are bothering you.
Frank Harrell

  
    
#
On Thu, 5 Feb 2009, cls59 wrote:

            
The syntax Sweave uses is fairly sensitive to backslashes. I might guess 
that this is a feature to protect against runaway expressions.

You need to add a backslash to undo what Sweave does to the backslashes in 
that type of expression.

Put

  	extra.slash <- function(x) sub('\\','\\\\', x, fixed=TRUE)

in an earlier code chunk and then call

 	\Sexpr(extra.slash( latexNum( 4*10^3 ) ) )

or better still just use a code chunk like this:

@
<<echo=F,results=tex>>
cat( latexNum( 4*10^3 ) )
@ %def

HTH,

Chuck
Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901
#
cls59 <sharpsteen <at> mac.com> writes:
I have my special version of it in the library :

"latexSNdouble" <-
function (val)
{
  # special copy of Hmisc latexSN with \\\\
  require(Hmisc)
  x <- format(val)
  x <- sedit(val, c("e+00", "e-0*", "e-*", "e+0*", "e+*"), c("",
        "\\\\!\\\\times\\\\!10^{-*}", 
        "\\\\!\\\\times\\\\!10^{-*}", 
        "\\\\!\\\\times\\\\!10^{*}", 
        "\\\\!\\\\times\\\\!10^{*}"))
  x
}