[R] gsub, backslash and xtable

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Aug 27 15:02:01 CEST 2004


"P. B. Pynsent" <p.b.pynsent at bham.ac.uk> writes:

> 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
...
> However I am very much left with the feeling that R is in control of
> me rather than vise versa.


The generic rule for backslashes is that you need twice as many as you
thought:

> p
[1] "25%"
> gsub("%","\\\\%",p)
[1] "25\\%"
> cat(gsub("%","\\\\%",p),"\n")
25\%

The thing that people usually forget is that you have two levels of
escaping, one in R's string parser and another one in the regexp
machinery. 

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list