[R] gsub, backslash and xtable

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Aug 27 15:03:43 CEST 2004


On Fri, 27 Aug 2004, P. B. Pynsent wrote:

> R Version 1.9.1  (2004-06-21)
> Mac OS X.3.5 Dual 2GHz PowerPC G5
> GUI = "AQUA"
> 
> 
> I have a data.frame comprising percentiles with the column headings 
> containing % characters, e.g.
>  > (pp <- colnames(temp2))
> [1] "5%"  "10%" "25%" "50%" "75%" "90%" "95%"
> I use xtable to convert the data.frame to Latex but I want to protect 
> these % signs from Latex using a backslash in the normal way before 
> calling xtable.
> I have tried using gsub as follows;
>  > gsub("\%","\\%",pp)
> [1] "5%"  "10%" "25%" "50%" "75%" "90%" "95%"
> also
>  > gsub("%","\134%",pp) #octal for backslash
> [1] "5%"  "10%" "25%" "50%" "75%" "90%" "95%"
> Both of which fail to provide what I need.

Remember you need to double \ in R character strings (in the FAQ, for 
example, and in ?regex):

>  gsub("%","\\\\%",pp)
[1] "5\\%"  "10\\%" "25\\%" "50\\%" "75\\%" "90\\%" "95\\%"
> cat(gsub("%","\\\\%",pp), "\n")
5\% 10\% 25\% 50\% 75\% 90\% 95\% 



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