[R] Sweave and backslashes
Charles C. Berry
cberry at tajo.ucsd.edu
Fri Feb 6 04:49:57 CET 2009
On Thu, 5 Feb 2009, cls59 wrote:
>
> 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
>
>> latexNum(4*10^-3)
>
> I get
>
> [1] "4\\cdot10^{-3}"
>
> And the following:
>
>> cat(latexNum(4*10^-3))
>
> Produces:
>
> 4\cdot10^{-3}
>
> However the following in a .Rnw file:
>
> $\Sexpr{latexNum(4*10^-3)}$\\
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
>
> 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
> --
> 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.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
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
More information about the R-help
mailing list