[R] Question on sub(stitute) X_1 -> X\_1

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Dec 1 10:29:53 CET 2006


You are confusing the printed representation with the string (a clue which 
is all over the archives, and in ?regex).

X1 <- sub("_","\\_","X_1",fixed=TRUE)
print(X1)
cat(X1, "\n")
X2 <- sub("_","\\\\_","X_1")
cat(X1, "\n")

both do as you ask.

On Fri, 1 Dec 2006, Christian Hoffmann wrote:

> Hi,
>
> Searching the archives has brought no clue:
>
> For a tex chunk in an Sweave text
>
> "Oracle query results: differences \Sexpr{varname},..."
>
> I need to change the string varname from "X_1" to "X\_1",
>
> sub("_",??,"X_+")  -> "X\_1"
>
> so that subsequent Latex will generate "X_1" (i.e. show the underscore)
> instead of "X subscript 1" (subscripting the "1")
>
> Various trials with sub("_","\\_",varname) and the like have not helped.
>
> sub("_","\\_","X_1")             -> "X_1"
> sub("_","\\_","X_1",fixed=TRUE)  -> "X\\_1"
> sub("_","\_","X_1",fixed=TRUE)   -> "X_1"
>
> Latex will translate  "X\\_1" to X  (linefeed) 1  !!
>
> Thanks for help
>
> Christian
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list