2

I want to export a latex table with a units column that has the percent (%) symbol.

library(xtable) 
foo <- data.frame(units='%', citation = '\\citep{authorYYYYabc}')
print(xtable(foo), sanitize.text.function = function(x) {x})

note: above code has been changed since Joris' answer.

In this case, the '%' is interpreted as a comment by LaTeX.

I have tried

gsub('%', '\\%', foo)

returns

[1] "1"

how can I convert the % to \% so that LaTex comments it out?

This question is a little bit like a previous question "can R paste('\')?"; even polishing the same table, but I can't figure out this particular case.

Community
  • 1
  • 1
David LeBauer
  • 31,011
  • 31
  • 115
  • 189

2 Answers2

2

I'm not sure if I understand you completely correctly. If I do xtable(foo), then the % is correctly escaped :

...
  \hline
1 & \% \\ 
   \hline
...

If you want to make an escape slash for something else, you need a quadruple one in gsub :

> x <- gsub('%', '\\\\%', foo[,1])
> x
[1] "\\%"
> cat(x,"\n")
\% 

Mind you, you cannot gsub in a dataframe, only in a vector. This can be shown by

> as.character(foo)
[1] "1"
Joris Meys
  • 106,551
  • 31
  • 221
  • 263
  • sorry, I made a mistake in my original question should I ask it again or make corrections above - I am using `print(xtable(foo), sanitize.text.function function(x) {x})` to properly convert citations in the dataframe: `foo <- data.frame(units='%', citation = '\\citep{authorYYYYabc}')` – David LeBauer Feb 17 '11 at 18:53
  • I apologize for changing the question and then selecting an answer to my revised question. I do appreciate the help. – David LeBauer Feb 17 '11 at 19:28
  • @David: no prob. But you should have found the answer of Sacha by yourself. Read also `?grep` and `?regex` to learn about regular expressions in R. You won't regret it. – Joris Meys Feb 18 '11 at 00:02
2

Combining Joris' answer with the codes in the comment:

library(xtable)
foo <- data.frame(units='%', citation = '\\citep{authorYYYYabc}')
print(xtable(foo), sanitize.text.function = function(x)gsub('%', '\\\\%', x))
Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131