[R] gsub, backslash and xtable

P. B. Pynsent p.b.pynsent at bham.ac.uk
Fri Aug 27 14:27:02 CEST 2004


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.

I verified  my 'regexps' using awk under Darwin thus;
$ cat fred
"5%"  "10%" "25%" "50%" "75%" "90%" "95%"
$ awk '{gsub(/%/,"\\%"); print}' <fred
"5\%"  "10\%" "25\%" "50\%" "75\%" "90\%" "95\%"
and
$ awk '{gsub(/%/,"\134%"); print}' <fred
"5\%"  "10\%" "25\%" "50\%" "75\%" "90\%" "95\%"

As a possble 'work around', I noticed that,
 > chartr("z","\",gsub("%","z%",pp))
Error: syntax error
 > chartr("z","\\",gsub("%","z%",pp))
[1] "5\\%"  "10\\%" "25\\%" "50\\%" "75\\%" "90\\%" "95\\%"
 > chartr("z","\134",gsub("%","z%",pp))
[1] "5\\%"  "10\\%" "25\\%" "50\\%" "75\\%" "90\\%" "95\\%"

As the xtable is then 'catted' to a file and read back (vide infra) I 
actually end up with what I want using the latter example.
However I am very much left with the feeling that R is in control of me 
rather than vise versa.



Secondly, as I am building up a character vector of sentences, tables 
and figures, I wanted to convert my xtable output to a character vector 
with newline
separators. I have only able to accomplish this by printing to a 
temporary file thus,

theTx <- "\\documentclass[A4paper,10pt]{article}"
.
.
theTx <- paste(theTx, paste_xtable(temp2,"Percentiles for scores"), sep 
= "")
.
theTx <- paste(theTx,"\n" ,"\\end{document}","\n", sep = "")
.
cat(theTx) #into a file for Latex

############## with my past_xtable function being ##########
paste_xtable <- function(a_table, cap) {
sink(file = "levzz", append = FALSE, type = "output")
print(xtable(a_table,caption=cap))
sink()
#read it  back
temp <- readLines("levzz", n=-1) #note / get doubled automaticaly
unlink("levzz") #delete file
a <- "\n"
for (i in 1:length(temp)) {
	a <- paste(a,temp[i],"\n",sep = "")
	}
return(a)
}

I should be most grateful for a  more elegant solutions to both these 
issues or a pointer to the documentation.

Paul




More information about the R-help mailing list