Like gsub ('%', '\%', ... in R?

I want to export a latex table with a unit column that has a percentage (%) character.

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

Note: the code above has been modified since Joris's answer.

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

I tried

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

returns

 [1] "1" 

How can I convert% to \% so that LaTex comments on this?

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

+2
source share
2 answers

Combining Joris answer with codes in a comment:

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

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

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

If you want to make a collage slash for something else, you will need a four in gsub:

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

Remember, you cannot gsub in a dataframe, only in a vector. It can be shown

 > as.character(foo) [1] "1" 
+2
source

All Articles